为什么绑定控制器模型不适用于服务模型的嵌套属性

时间:2014-12-16 16:28:34

标签: angularjs angularjs-directive angularjs-scope

Here is fiddle example。对我来说,隐式$ watch在simpleAlertCtrl中不起作用。但是当模型发生变化时,我可以明确指出需要提取哪个服务模型属性。你能提供更复杂的解释,为什么simpleAlertCtrl绑定不起作用?!

<body ng-app="MyApp">  
<br/><div id="alert" ng-show="show" ng-controller="watchAlertCtrl">
    <div class="alert alert-success">
        Alert text: {{message}}
    </div>     
</div>    
<br/><div id="alert" ng-show="show" ng-controller="simpleAlertCtrl">
    <div class="alert alert-info">
        Alert text: {{message}}
    </div>     
</div>  
<br/><div ng-controller="anotherCtrl">
    <button ng-click="Inc()">Increment</button>
</div>
</body>


var app = angular.module("MyApp", []);

app.factory('sharingData', function () {
    var alert = {};
    alert.show = true;
    alert.message = " ";
    return { alert: alert };
});

app.controller("watchAlertCtrl", function($scope, sharingData) {   
    $scope.$watch(function(){
        return sharingData.alert;
    }, function(value){
        console.log(value);
        $scope.message = value.message;
        $scope.show = value.show;
    },true);
});

app.controller("simpleAlertCtrl", function($scope, sharingData) {   
    $scope.message = sharingData.alert.message;
    $scope.show = sharingData.alert.show;
});

app.controller("anotherCtrl", function($scope, sharingData) {
    $scope.count = 0;
    $scope.Inc = function (){
        $scope.count ++ ;
        sharingData.alert.message = $scope.count.toString();
    };
});

1 个答案:

答案 0 :(得分:0)

根据您的问题和您的小提琴示例回答

首先,仅当引用的内容发生变化时,绑定到$scope的数据才会被双重绑定。例如,在您的情况下,anotherController如果您这样做

sharingData.alert.message = 'some new value';

然后在simpleAlertCtrl中,$scope.message仍将绑定到旧值:因为字符串变量的引用在此其他控制器中不会更改。你宁愿绑定一个参考不会改变的对象:

app.controller("alertCtrl", function($scope, sharingData) {
  $scope.alert = sharingData.alert;
});

另一方面,如果要观看表达式,请查找该表达式。例如,在anotherController中,当事件发生时,您要么在其范围内查找text表达式,要么返回返回$scope.text的函数(对应于用户的输入)< / p>

app.controller("anotherCtrl", function($scope, sharingData) {
    $scope.$watch('text', function(value){
        sharingData.alert.message = value;
        sharingData.alert.show = true;
    });
});

工作小提琴:http://jsfiddle.net/nqscd124/1/