我有一个例子Plunker 。为什么绑定(bind)到 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; }; });
最佳答案
因为变量不是通过引用传递的,而是通过值传递的。
为了实现这一目标,您必须这样做:
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()}}
关于javascript - 为什么 Angular 绑定(bind)不适用于服务原语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29096573/