我可以用一个控制器AngularJS更新两种观点? [英] Can I use one controller updating two views in AngularJS?

查看:91
本文介绍了我可以用一个控制器AngularJS更新两种观点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能,有绑定到一个控制器两种观点,这样既看法得到更新无论身在何处的数据被改变(视图1,视图2或模型)?它应该像这个例子中(去除杂波)。

Is it possible, to have two views bound to one controller, so that both views get updated no matter where the data was changed (view1, view2 or in the model)? It should work like this example (removed clutter).

<script>
    angular.module('foobar', []).controller('ContentCtrl', ['$scope', function($scope) {
        $scope.content = {'title': 'Foo', 'subtitle': 'Bar', 'text': 'desc'};
    }]);
</script>

<form action="#" ng-controller="ContentCtrl">
    <input type="text" ng-model="content.title">
    <input type="text" ng-model="content.subtitle">
    <textarea ng-model="content.text"></textarea>
</form>

<div ng-controller="ContentCtrl">
    <input type="text" ng-model="content.title">
    <input type="text" ng-model="content.subtitle">
    <textarea ng-model="content.text"></textarea>
</div>

下面是一个Plunker: http://plnkr.co/edit/UDs10​​RhG7mJR8813epwO? p = preVIEW

Here is a Plunker: http://plnkr.co/edit/UDs10RhG7mJR8813epwO?p=preview

推荐答案

有没有理由,你不能做到这一点,但同样的对象是在两个控制器的范围。请参见 http://plnkr.co/edit/ILzGCs9AYiPTETE92KTm?p=$p$pview

There's no reason you can't do this, but the same object has to be in the scope of both controllers. See http://plnkr.co/edit/ILzGCs9AYiPTETE92KTm?p=preview

在原来的例子中,每个范围都有它自己的对象,所以每次自己的对象上运行。如果这两个范围共享同一个对象,那么每一个被相同的对象上操作的,因此,在一个范围的变化反映在其他

In the original example, each scope has it's own object, and so each is operating on their own object. If both scopes share the same object, then each is operating on the same object, and thus changes in one scope is reflected in the other.

这篇关于我可以用一个控制器AngularJS更新两种观点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆