我做了相当简单的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)' –