2013-11-15 154 views
0

我目前正在填充$scope陣列像最簡單的方法:

$scope.categories = []; 

$scope.getCategories = function() { 
    ItemService.getCategories().success(function(categories) { 
     $scope.categories = categories; 
    }); 
} 

$scope.getCategories(); 

這真的是做到這一點的最簡單的方法?

+0

難的部分在哪裏? –

+0

這並不難,只是很多代碼 – Pixark

+1

爲什麼將服務調用包裝在範圍函數中?除非您的界面通過某些事件觸發它,否則不需要。另外,如果你想在控制器初始化時加載類別,你應該看看在路由的解析函數中執行它,或者如果你不使用路由,那麼在應用程序的運行函數中。 –

回答

3

你確實需要一個getCategories函數嗎?如果這是唯一被調用的地方,那麼您可以直接刪除並直接離開服務電話。

否則,您的代碼與使用承諾所用的代碼一樣短,我認爲,如果您使用的是v1.2。在1.2之前,角度確實有自動承諾解包。也就是說,不是

//$scope.getCategories = function() { 
    ItemService.getCategories().success(function(categories) { 
     $scope.categories = categories; 
    }); 
//} 

你能做到這一點,而不是,這似乎更優雅:

//$scope.getCategories = function() { 
    $scope.categories = ItemService.getCategories(); 
//} 

使用問題,意味着它最近被刪除,雖然 - https://github.com/angular/angular.js/issues/4158。我認爲如果還有一個好方法可以在將來添加替代品。

0

您可以簡單地使用路由器的resolve屬性(假設您使用的是路由器)將結果從ItemService.getCategories()注入您的控制器。 resolve屬性阻止完成路線直到完全解決 - 它會自動解開承諾。該代碼看起來像這樣:

angular.module('MyModule').config(function ($routeProvider) { 
    $routeProvider.when('/mypage', { 
     templateUrl: '/mypage.html', 
     controller: 'MyController', 
     resolve: { 
      categories: function (ItemService) { return ItemService.getCategories(); } 
     } 
    }); 
}); 

angular.module('MyModule').controller('MyController', function (categories, $scope) { 
    $scope.categories = categories; 
});