Angularjs - Updating multiple instances of the same controller

心已入冬 提交于 2019-12-11 11:14:56

问题


My problem: I have multiple instances a controller in my site. When I update 'x', only the current instance/div gets updated.

JSFiddle: http://jsfiddle.net/evgahe2u/ (simplified example, each ng-controller is in its own view.)

HTML

<!-- this is a simplified example -->
<div ng-app="myApp">
       <!-- this is in view1.html -->
        <div ng-controller="myController">
                <input type="text" ng-model="x" /> {{x}}
        </div>
        <!-- this is in view2.html -->
        <div ng-controller="myController">
                <input type="text" ng-model="x" /> {{x}}
        </div>
</div>

JS

var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope) {
    $scope.x = 'test';
});

My question: How can I have it so when I update View1.html's X value, it will then update view2.html's view?


回答1:


That's pretty easy.

According to me the best way to do this is to create a factory.

Let's say factory X and let's create two controllers for both views:

myApp.controller('1Ctrl', function($scope, x) {
  $scope.x = x.x;
});

myApp.controller('2Ctrl', function($scope, x) {
  $scope.x = x.x;
});

myApp.factory('x', function() {
  return {
    x: 'value'
  };
});

Full Example: JSFiddle

Now if X is updated it will update in both controllers, because of the properties of an object. Both x'es on both scopes are the same x.




回答2:


Broadcast from rootScope

$rootScope.$broadcast("changeXevent", dataToSend);

then handle it with an $on in the controller.

myApp.controller('myController', function($scope, $rootScope) { // inject rootscope
    $scope.x = 'test';

    // watch for event
    $scope.$on('changeXevent', function(event, data){
         $scope.x = data;
    });

    // watch for changes on x
    $scope.$watch('x', function(newValue, oldValue){
        if(newVal !== oldVal)
            $rootScope.$broadcast('changeXevent', $scope.x);
    });

});


来源:https://stackoverflow.com/questions/26895567/angularjs-updating-multiple-instances-of-the-same-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!