0

I'm starting using Angular JS to build a mobile application with Ionic.

I'm trying a thing very simple but it does not work.

HTML

<div ng-controller="MyCtrl">
  Hello, {{name}}!
</div>

<div ng-controller="MyCtrl2">
   Hello, {{name}}!
</div>

<button ng-controller="MyCtrl" ng-click="MyCtrl.test()">click</button>

JS

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.name = 'Name 1';
    $scope.test = function () {
        $scope.name = 'Name on click !';
    }
}

function MyCtrl2($scope) {
    $scope.name = 'Name 2';
}

I have a similar structure in my Ionic App. I need to modify the "$scope.name" from another template. Thanks for help.

JSFiddle : http://jsfiddle.net/ADukg/6649/

jlafforgue
  • 287
  • 2
  • 5
  • 15
  • http://jsfiddle.net/dulcedilip/40h03njm/ check with this fiddle, scope is the issue button is outside the div context. the below comment is correct. – Dilip Tirumala Jun 01 '15 at 10:27

2 Answers2

2

This Fiddle will provide you with a working copy of your code.

<div ng-controller="MyCtrl"> 
    <div>
        Hello, {{name}}!
    </div>
    <div ng-controller="MyCtrl2">
        Hello, {{name}}!
    </div>
    <button ng-click="test()">click</button>
</div>

(function() {

    function MyCtrl($scope) {
        $scope.name = 'Name 1';
        $scope.test = function() {
            $scope.name = 'Name on click !';
        };
    }

    function MyCtrl2($scope) {
        $scope.name = 'Name 2';
    }

    angular.module('myApp', [])
        .controller('MyCtrl', MyCtrl)
        .controller('MyCtrl2', MyCtrl2);

})();

You missed the following:

  1. Assigning your controllers to your module
  2. Wrapping the required template html in your ng-controller instead of declaring it twice.
Joshua Kelly
  • 1,023
  • 8
  • 12
1

To modify scope from another controller you need to use either $rootScope or angular js sevice .

Here is the $rootScope example:

angular.module('myApp', [])
.run(function($rootScope) {
    $rootScope.test = new Date();
})
.controller('myCtrl', function($scope, $rootScope) {
  $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
})
.controller('myCtrl2', function($scope, $rootScope) {
    $scope.change = function() {
        $scope.test = new Date();
    };

    $scope.changeRs = function() {
        $rootScope.test = new Date();
    };

    $scope.getOrig = function() {
        return $rootScope.test;
    };
})
Community
  • 1
  • 1
NewDirection
  • 116
  • 10
  • You don't want to be attaching stuff to the rootScope though unless you really have to. If you're going to pass it around your application and not between two controllers in the same partial, it's much better to create a service. – Joshua Kelly Jun 01 '15 at 10:05
  • I just described available ways, services indeed better but rootscope also a 'not so good' way – NewDirection Jun 01 '15 at 10:11