Angular工厂不返回对象属性

时间:2016-08-02 21:46:39

标签: angularjs object properties

我可以返回一个对象,但不能返回object属性。为什么?我尝试过很多东西,但似乎没什么用。对不起,我是Angular的新人

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

  var data = {
    product: ''
  };


  function addItem(value) {
    data.product = value;
  }

  function getList() {
    return data.product;
  }

  return {
    addItem: addItem,
    getList: getList
  };

});

更新了控制器功能

function controllerA(myData){

  var scope = this;
  scope.total = 0;

  scope.addMore = function(){
    scope.total++;
    myData.addItem(scope.total);
  }

}

function controllerB(myData){

  var scope = this;
  scope.total = 0;
  scope.total = myData.getList();

}

2 个答案:

答案 0 :(得分:1)

当控制器被实例化时,控制器B中的总数被初始化。

调用addMore()时,控制器A中的总数被修改。因此,如果在实例化控制器B之后调用addMore() ,则控制器B将始终引用原始值或总数:空字符串:

 t0: controller A is instantiated
 t1: controller B is instantiated. B.total is initialized with the result of myData.getList(), which is the empty string:

   data.product -------\
                       |
                       V
   B.total -------> empty string


 t2: a.addMore() is called. That modifies the service's total, but not the variable in B

  data.product ---> 1


   B.total -------> empty string

如果您在控制器中引用对象本身,则不会出现此问题,因为B对数据有引用,而data.product由A修改。

答案 1 :(得分:0)

你可以阅读好文章:

aticle

  demo.factory(
            "Friend",
            function( trim ) {
                // Define the constructor function.
                function Friend( firstName, lastName ) {
                    this.firstName = trim( firstName || "" );
                    this.lastName = trim( lastName || "" );
                }
                // Define the "instance" methods using the prototype
                // and standard prototypal inheritance.
                Friend.prototype = {
                    getFirstName: function() {
                        return( this.firstName );
                    },
                    getFullName: function() {
                        return( this.firstName + " " + this.lastName );
                    }
                };
                // Define the "class" / "static" methods. These are
                // utility methods on the class itself; they do not
                // have access to the "this" reference.
                Friend.fromFullName = function( fullName ) {
                    var parts = trim( fullName || "" ).split( /\s+/gi );
                    return(
                        new Friend(
                            parts[ 0 ],
                            parts.splice( 0, 1 ) && parts.join( " " )
                        )
                    );
                };
                // Return constructor - this is what defines the actual
                // injectable in the DI framework.
                return( Friend );
            }
        );