Angularjs - 无法将服务返回值加载到$ scope

时间:2018-01-26 07:59:31

标签: angularjs service scope

我正在使用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();
         });

2 个答案:

答案 0 :(得分:1)

在服务中声明功能时使用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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

将其更改为

get