我做了很简单plunker来表明我的问题。问题是我有变量,我想用初始app加载来填充这个变量,我为此目的做了角度服务,但由于某种原因,角度服务不会在控制器内部触发。我的错误在哪里?
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
}
}])
}());
答案 0 :(得分:2)
您应该执行以下服务声明:
app.controller('MainCtrl', ['$scope', 'optService', function($scope, optService) {
并在控制器中
optService.myOptions().then(function (result) {
console.log('service fired')
angular.forEach(result, function(value) {
$scope.priority.push({value: value.name, label: value.name});
});
});