AngularJS工厂财产不被在$范围不使用时推(更新) [英] AngularJS factory property isn't being updated in $scope when not using push()

查看:149
本文介绍了AngularJS工厂财产不被在$范围不使用时推(更新)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工厂,从外部源检索数据。当我得到的数据,我用第二工厂通过一定的标准对其进行过滤。

I have a factory that is retrieving the data from an external source. As soon as i get the data, i use a second factory to filter it by a certain criteria.

工厂属性分配范围。

现在当我做这在我的工厂,它不更新的范围:

Now when i do this in my factory, it doesn't update the scope:

factory.foo = [{id:1,name:'foo'}]; // doesn't work

也为此在第二工厂filterin不起作用

therefor also the filterin in a second factory doesn't work

factory.foo = Filter.filter(); // doesn't work

而这个作品:

factory.foo.push({id:1,name:'foo'}); // works

没有任何人有一个想法,如果这样做的目的,为什么它是这样的,如何解决它?

Does anyone have an idea if this is intended and why it is like this, and how to solve it?

全样本加上plunkr

app.factory('Foo',function(Filter) {
  var factory = {
    foo:[],
    getDataForFoo:function() {
      factory.foo = Filter.filter(); // doesn't work
      //factory.foo = [{id:1,name:'foo'},{id:1,name:'foo'}]; // doesn't work
      //factory.foo.push({id:1,name:'foo'}); // works
    }
  };
  return factory;
});

app.factory('Filter',function() {
  var factory = {
    filter:function() {
      var arr = [];
      arr.push({id:1,name:'foo'});
      return arr;
    }
  }
  return factory;
});

app.controller('MainCtrl', function($scope,Foo) {
  $scope.test = 'running';
  $scope.foo = Foo.foo;

  $scope.click = Foo.getDataForFoo;
});

Plunkr

推荐答案

的问题是,你的工厂替换参考 Factory.foo 。当你的范围被初始化, $ scope.foo 保存到一个数组(空)的引用。当你调用 Foo.getDataForFoo ,它在内部改变参照 Factory.foo 但是你的范围仍然坚持参考在previous阵列。这就是为什么使用工作,它不会改变数组引用,但数组的内容。

The problem is that your factory replace the reference to Factory.foo. When your scope is initialized, $scope.foo holds a reference to an array (empty). When you call Foo.getDataForFoo, it internally changes the reference to Factory.foo but your scope still hold a reference to the previous array. This is why using push works as it doesn't change the array reference, but the array content.

有几种方法来解决这个问题。如果没有所有不同的选择去,最简单的一种是包装你的 $ scope.foo 在一个函数,返回 Factory.foo 。通过这种方式,将角检测摘要周期参考的变化并相应地更新视图。

There are a few ways to fix this. Without going in all the different options, the easiest one is to wrap your $scope.foo in a function, returning Factory.foo. This way, Angular will detect a reference change in a digest cycle and will update the view accordingly.

app.controller('MainCtrl', function($scope,Foo) {
  $scope.test = 'running';
  $scope.foo = function() { return Foo.foo };

  $scope.click = Foo.getDataForFoo
});

// And in the view (the relevant part)

<ul ng-repeat="elem in foo()">
  <li>{{elem.id}} {{elem.name}}</li>
</ul>
<a href="" ng-click="click()">add</a>

这篇关于AngularJS工厂财产不被在$范围不使用时推(更新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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