2014-01-30 31 views
0

我正在創建一個AngularJS指令以便使用D3來渲染可視化,但是當涉及到設置$watch時,我遇到了問題。我的大部分東西看起來與AngularJS教程非常相似。我的資源配置在一個名爲resources.json的文件中,我確定它正確返回。

這裏是我到目前爲止的相關代碼:

app.js

var resourceApp = angular.module("resourceApp", [ 
    'ngRoute', 
    'resourceControllers', 
    'resourceDirectives', 
    'resourceServices' 
]); 

/* ... routing config ... */ 

controllers.js

var resourceControllers = angular.module('resourceControllers', []); 

resourceControllers.controller("OverviewCtrl", [ '$scope', 'Resource', 
    function($scope, Resource) { 
     $scope.resources = Resource.query(); 
    } 
]); 

/* ... other controllers ... */ 

directives.js

var resourceDirectives = angular.module('resourceDirectives', []); 

resourceDirectives.directive("resourceVisualization", function() { 
    return { 
     restrict: 'E', 
     scope: { 
      resources: '=' 
     }, 
     link: function(scope, el, attrs) { 
      // svg setup is here 

      scope.$watch("resources", function(nRes, oRes) { 
       if (nRes) { 
       // this logs an array of Resource objects 
       //(once expanded in Firebug) 
       console.log(nRes); 

       var cats = nRes.map(function(r) { return r.category; }); 
       // this logs an empty array 
       console.log(cats); 
       } 
      }); 
     } 
    }; 
}); 

概述.html

<ul> 
    <li ng-repeat="resource in resources"> 
     {{resource.name}} 
    </li> 
</ul> 
<resource-visualization resources="resources"></resource-visualization> 

resources.json(這是什麼services.js被配置爲從拉)

[ 
{ 
    "id": 1, 
    "category": "test", 
    "type": "sample", 
    "name": "Test1" 
}, 
{ 
    "id": 2, 
    "category": "test", 
    "type": "sample4", 
    "name": "Test2" 
}, 
{ 
    "id": 3, 
    "category": "fake", 
    "type": "sample1", 
    "name": "Test3" 
}, 
{ 
    "id": 4, 
    "category": "new", 
    "type": "sample2", 
    "name": "Test4" 
}] 

現在,我知道,REST調用工作,因爲<ul>填充。但是,在指令中,日誌語句正在返回空數組。我知道$resource的異步性,但在$watch中首先記錄的對象包含$resolved: true

我錯過了什麼嗎?

+0

你100%確定nRes是一個數組嗎?你有沒有試過在你傳遞給映射的回調函數中粘貼一個日誌,看看它是否遍歷每個元素? –

+0

另外,您確定'nRes'包含包含'category'的項目。真的,nRes是什麼樣的。 – TheSharpieOne

+0

@ net.uk.sweet:是的,它絕對是一個數組。 'console.log(nRes)'語句在Firebug中顯示爲一個數組。 @TheSharpieOne:現在更新問題以顯示資源的JSON文件(填充'nRes'的樣子) – Pat

回答

1

這一切都很好。您撥打Resource.query()的電話將立即返回一個空數組。如果ajax調用返回實際的數據,你的數組將填滿到達的數據。因此,第一個分配到$scope.resources會使用空數組激發您的$watch函數。如果您使用$watchCollection功能,您可以解決您的問題。有關更多信息,請參閱http://docs.angularjs.org/api/ng.$rootScope.Scope

+0

因爲它是一個集合,所以'$ watchCollection'就是我所需要的。再次感謝! – Pat

相關問題