我正在使用angularjs,我正在尝试将服务中的值解析为我的$scope控制器。问题是首先加载$scope,然后加载服务。因此,我的范围总是不确定的。我尝试了许多解决方案,但我发现没有人适合我。谁能帮我?我的服务:
'use strict';
angular.module('myApp')
.service('getCategoriesService', function ($rootScope) {
getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
和我的控制器:
angular.module("myApp")
.controller('MyCtrl', function ($scope,getCategoriesService) {
$scope.resultCategory = getCategoriesService.getCategories();
});
在服务中声明函数时使用this.
。
.service('getCategoriesService', function ($rootScope) {
this.getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
})
演示
var app = angular.module("myApp",[]);
app.controller('MyCtrl', function ($scope,getCategoriesService) {
$scope.resultCategory = getCategoriesService.getCategories();
});
app.service('getCategoriesService', function ($rootScope) {
this.getCategories = function () {
var categoriesByLocation = 1;
return categoriesByLocation;
};
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
{{resultCategory}}
</div>
将其更改为
angular.module("myApp")
.controller('MyCtrl', function ($scope,getCategoriesService) {
getCategoriesService.getCategories().then((function (d) {
$scope.resultCategory = d;
}
});