结合原来的对象更改时不会更新 [英] Binding doesn't update when the original object changes

查看:72
本文介绍了结合原来的对象更改时不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我误解了一些关于数据绑定和范围如何角工作,或者我在Javascript中的一些误解一般。我希望有人能帮助我。

I think I have misunderstood something about how data-binding and scopes work in Angular, or maybe I have some misconception in Javascript in general. I hope somebody can help me.

让我们说我有一个工厂,都有一个对象,并定义一个getter / setter方法​​吧:

Let's say I have a factory that has an object, and defines a getter/setter for it:

app.factory('myFactory', function(){

    var myObject : {

        subObject : {

             subProperty : 'value'
        }
    };

    return {

        getObject : function() {

            return myObject;
        },

        setObject : function(obj) {

            myObject = obj;
        }
    };
};

然后,在控制器我得到这个对象和子对象分配到的范围:

Then, in a controller I get this object and assign the subObject to the scope:

app.controller('myController', function($scope, myFactory){

    var myObject = myFactory.getObject();

    $scope.subObject = myObject.subObject;
});

在视图中,我绑定到该对象的子属性:

In the view, I bind to the subProperty of that object:

<div> {{subObject.subProperty}} </div>

随后,有人拨打了myFactoy.setObject()方法,并在工厂的一个新的取代了原来的对象。
应该不是我的绑定自动更新?如果它不应该...这是为了做到这一点?最好的办法

Then, somebody calls the myFactoy.setObject() method and replaces the original object in the factory for a new one. Shouldn't my binding be updated automatically?? if it shouldn't... which is the best way to accomplish this??

推荐答案

原来的对象不会改变。你只是改变了引用。

The original object doesn't change. You're just changing the reference to it.

使用这个代替:

setObject : function(obj) {

    angular.copy(obj, myObject);
}

这篇关于结合原来的对象更改时不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆