我有一个例子Plunker。为什么绑定到count: 0
不起作用?这是来自* .js文件的代码:
var app = angular.module("MyApp", []);
app.controller("objectCtrl", function($scope, sharingData) { $scope.message = sharingData.message; });
app.controller("primitiveCtrl", function($scope, sharingData) { $scope.count = sharingData.message.count; });
app.controller("watchCtrl", function($scope, sharingData) { $scope.message = {};
$scope.$watch(function() {
return sharingData.message.count; }, function(value) {
$scope.message.count = value; }); });
app.factory('sharingData', function() { return {
count: 0,
message: {
count: 0
} }; });
app.run(function($rootScope, sharingData) { $rootScope.Inc = function() {
sharingData.message.count = ++sharingData.count; }; });
答案 0 :(得分:2)
因为变量不是通过引用传递的,而是通过值传递的。
为了达到这个目的,你不得不这样做:
app.controller("primitiveCtrl", function($scope, sharingData) {
$scope.count = sharingData.message;
});
和
count from primitiveCtrl: {{count.count}}
http://plnkr.co/edit/h8A8PwGJuhD2imRbEsNM?p=preview
编辑:事实是,在javascript中无法通过引用传递原始值。可能类似于此的一件事如下:
app.controller("primitiveCtrl", function($scope, sharingData) {
$scope.getValue= function(){
return sharingData.message.count;
};
});
和
count from primitiveCtrl: {{getValue()}}