我有一个例子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; }; });
因为变量不是通过引用而是通过值传递。
为了实现这一点,您必须这样做:
app.controller("primitiveCtrl", function($scope, sharingData) {
$scope.count = sharingData.message;
});
和:
count from primitiveCtrl: {{count.count}}
http://plnkr.co/edit/h8A8PwGJuhD2imRbEsNM?p=预览
编辑:事实是,不可能通过引用在javascript中传递原始值。可能与此类似的一件事是:
app.controller("primitiveCtrl", function($scope, sharingData) {
$scope.getValue= function(){
return sharingData.message.count;
};
});
和:
count from primitiveCtrl: {{getValue()}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句