【问题标题】:Angular watch array in service服务中的角手表阵列
【发布时间】:2016-08-23 01:03:17
【问题描述】:

我正在尝试查看服务中的数组并且真的很挣扎。

服务

angular.module('starter.entities',[]).service('Entities', function() {
var _entities = this;

// public API
 this.locations = [];

 document.body.addEventListener("dbready", function(){
  buildModel(function(locations) {
    _entities.locations = locations;
   });
 });

控制器

  .controller('DashCtrl', function($scope, Entities) {

    $scope.$watch(function() { return Entities.locations }, function() {
     doSomething...
   }, true);

.....

基本上它是在数据库中加载数据,我想在加载数据时更新 UI。

watch 函数在第一次加载发生时被调用,而不是在数据加载发生时被调用。

有没有一种简单的方法可以让 $watch 发生?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    来自AngularJS框架之外的事件需要用$apply通知框架模型的变化。

    app.service('Entities', function($document, $rootScope) {
        var self = this;
    
        // public API
        this.locations = [];
    
        $document.find("body").on("dbready", function(){
          buildModel(function(locations) {
            self.locations = locations;
            //Use $apply to notify AngularJS framework
            $rootScope.$apply();
        });
    
    });
    

    有关详细信息,请参阅AngularJS $rootScope.scope API Reference -- $apply

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 2011-09-12
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多