Angularjs - 更新同一个控制器的多个实例 [英] Angularjs - Updating multiple instances of the same controller
问题描述
我的问题:我有多个实例在我的网站控制器。当我更新'X',只有当前实例/ DIV得到更新。
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/ (简化例如,每个NG-控制器在自己的看法。)
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';
});
我的问题:我怎么能有这么当我更新View1.html的X值,它会再更新view2.html的看法
My question: How can I have it so when I update View1.html's X value, it will then update view2.html's view?
推荐答案
这是pretty容易。
That's pretty easy.
据我做到这一点的最好办法是创建一个工厂。
According to me the best way to do this is to create a factory.
比方说,工厂X和让我们创建两个控制器为两种观点:
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'
};
});
完整的例子:的jsfiddle
现在如果X被更新,将在两个控制器更新,因为对象的属性。在两个范围都x'es都是相同的x。
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.
这篇关于Angularjs - 更新同一个控制器的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!