Hareesh
Hareesh

Reputation: 734

understanding the controller scope in angularJS

Consider two div areas as follows, in html file

<div class="divArea1" ng-controller="myController">
   <input ng-click="updateName()" type="button" value="button"/>
</div>

<div class="divArea1" ng-controller="myController">
  <p>{{name}}</p>
</div>

Following is the angular js example

productApp.controller("myController", [ '$scope', function($scope) {
    $scope.name= "XYZ";
    $scope.updateName= function() {
        $scope.name = "ABC";
    };
} ]);

problem is when I am trying to update the name, upon click on update button it is not visible in the second in the div area. Is there any mistake i am doing.

Upvotes: 1

Views: 98

Answers (3)

Deblaton Jean-Philippe
Deblaton Jean-Philippe

Reputation: 11388

Controllers are not singletons. Each time you have a new controller, you're having a new instance of this controller, with a new isolated scope.

If your need is to share data between controllers, you should use a factory (which is a singleton).

angular.module('app').factory('mySharedData', function(){
   var service = {
       object : objectToShare
   };

   var objectToShare =  {};

   return service;
});

And from your controller :

angular.module('app').controller('myController', 
    ['$scope','mySharedData', 
    function($scope, mySharedData){
        $scope.someObject = mySharedData.object;
        $scope.updateName= function() {
            $scope.someObject.name = "ABC";
        };
    }
]);

And from your view :

<div class="divArea1" ng-controller="myController">
   <input ng-click="updateName()" type="button" value="button"/>
</div>

<div class="divArea1" ng-controller="myController">
  <p>{{someObject.name}}</p>
</div>

Note : I've encapsulated the name property into an object because objects are passed by reference, and strings by value. This allows you to make it easier to share your values and to have it automatically updated into the service and other controllers, without having to access your property through accessors.

Upvotes: 0

Jayant Patil
Jayant Patil

Reputation: 1587

here is demo http://jsfiddle.net/wg7pb1yu/3/ inject $rootScope so that it will do from global scope

productApp.controller("myController", [ '$scope','$rootScope', function($scope, $rootScope) {
$rootScope.name= "XYZ";
$scope.updateName= function() {
    $rootScope.name = "ABC";

};} ]);

Hope this will help you

Upvotes: 0

sailens
sailens

Reputation: 1614

What you have is two different controllers (with two separate scopes) with the same name.

You need to put the controller in the parent controller to keep the name in the same scope as the button:

<div id="container" ng-controller="myController">
   <div class="divArea1">
      <input ng-click="updateName()" type="button" value="button"/>
   </div>

   <div class="divArea1">
     <p>{{name}}</p>
   </div>
</div>

Upvotes: 1

Related Questions