我有一個服務和一個位指示一個角應用程式:AngularJS - 訪問在另一個方法返回範圍方法變量
service.js
.factory('MyService', function ($http, $q) {
var api_url = 'http://localhost/api/';
var MyService = {
list: function (items_url) {
var defer = $q.defer();
$http({method: 'GET',
url: api_url + items_url}).
success(function (data, status, headers, config) {
defer.resolve(data);
}).error(function (data, status, headers, config) {
defer.reject(status);
});
return defer.promise;
},
...
}
});
controller.js
.controller("ItemsCtrl", function ($scope, MyService) {
$scope.getItems = function() {
MyService.list('items/').then(function(data) {
$scope.items = data;
});
};
$scope.addItems = function() {
$scope.getItems();
// why is this undefined ??!!!
console.log($scope.items);
};
問題是我想調用中的方法方法。我是否需要使用$scope.apply()
,因爲返回的值是一個承諾?
我想我在這裏顯示是一個普遍缺乏瞭解:/
任何幫助將非常感激。