javascript - 为什么 Angular 绑定(bind)不适用于服务原语

标签 javascript angularjs

我有一个例子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()}}

http://plnkr.co/edit/h8A8PwGJuhD2imRbEsNM?p=preview

关于javascript - 为什么 Angular 绑定(bind)不适用于服务原语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29096573/

相关文章:

AngularJS ng-required 不能使用变量

javascript - $apply 不适用于后退按钮提示的位置更改

javascript - AngularJS 和 map API : stop prompting for computer's location

AngularJS ui-route 退出页面

javascript - angular ngShow 与 animate.css

javascript - 大十进制 : how to set up the scale once

javascript - 将 jQuery $.when 和 $.then 与两个函数一起使用

javascript - 仅切换单击的行,并使用 JQuery 进行复选框

javascript - 使用 CKEditor 5 将段落锁定在一起

javascript - 迭代数据库中的对象