我做了相當簡單的plunker來顯示我的問題。問題是我有變量,我想用最初的應用程序加載填充這個變量,我爲此做了角度服務,但由於某些原因,角度服務不會在控制器內部激發。我的錯誤在哪裏?角度服務不會觸發
app.controller('MainCtrl', function($scope, optService) {
$scope.priority = [];
var exeService = function() {
console.log('function fired')
// this is firing
optService.myOptions(function (result) {
console.log('service fired')
// this is not firing
angular.forEach(result, function(value) {
$scope.priority.push({value: value.name, label: value.name});
});
});
}
exeService()
console.log($scope.priority)
// shows an empty array
});
服務
(function() {
angular.module("app").factory("optService", ["$http", "$rootScope", "$q", "$log",
function ($http, $rootScope, $q, $log) {
var clearApi = "test.json";
function myOptions() {
return $http.get(clearApi)
.then(function (response) {
console.log(response.data)
// shows an array
return response.data;
});
}
return {
myOptions: myOptions
}
}])
}());
功能'myOptions'在服務定義沒有任何爭論,所以你爲什麼要在你的控制器中調用'optService.myOptions(function(result)' –