Angularjs - 更新同一控制器的多个实例 [英] Angularjs - Updating multiple instances of the same controller

查看:14
本文介绍了Angularjs - 更新同一控制器的多个实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题:我的站点中有多个控制器实例.当我更新 'x' 时,只有当前实例/div 被更新.

JSFiddle: http://jsfiddle.net/evgahe2u/(简化例如,每个 ng-controller 都有自己的视图.)

HTML

<div ng-app="myApp"><!-- 这是在 view1.html 中--><div ng-controller="myController"><input type="text" ng-model="x"/>{{X}}

<!-- 这是在 view2.html 中--><div ng-controller="myController"><input type="text" ng-model="x"/>{{X}}

JS

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

我的问题:我怎样才能在更新View1.html的X值时更新view2.html的视图?

解决方案

这很简单.

我认为最好的方法是创建一个工厂.

假设工厂 X,让我们为两个视图创建两个控制器:

myApp.controller('1Ctrl', function($scope, x) {$scope.x = x.x;});myApp.controller('2Ctrl', function($scope, x) {$scope.x = x.x;});myApp.factory('x', function() {返回 {x:'值'};});

完整示例:JSFiddle

现在,如果 X 被更新,它将在两个控制器中更新,因为对象的属性.两个作用域上的 x 都是相同的 x.

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?

解决方案

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.

这篇关于Angularjs - 更新同一控制器的多个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆