简体   繁体   中英

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.

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>

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM