【问题标题】:view not gathering data from service through controller查看不通过控制器从服务中收集数据
【发布时间】:2013-08-21 20:48:56
【问题描述】:

无法加载外部 json 文件并将其内容显示在我的视图中。我已经包含了我的视图、控制器和服务代码。我需要改变什么?

view.html

<div ng-controller='BaseCtrl'>
    <table class="table table-hover">
        <tbody>
           <tr class="tr-sep" ng-repeat="example in examples" ng-click="showUser(example)">
              <td>{{example.name}}</td>
              <td>{{example.type}}</td>
              <td>{{example.size}}</td>
           </tr>
        </tbody>
    </table>
</div>

controller.js

'use strict';

angular.module('projyApp')
  .controller('BaseCtrl', function ($scope, data) {
    $scope.examples = data.getAllExamples();

    $scope.showUser = function(example) {
        window.location = '#/user/' +example.size;
    };

  });

service.js

'use strict';

angular.module('projyApp')
  .service('data', function data() {
        var examples;

        var getAllExamples = function () {

            $http.get("../../TestData/Examples.json").success($scope.examples = data.examples);
        };

  });

【问题讨论】:

  • 在您的服务中,您需要返回 data.examples 而不是将其分配给 $scope。 $scope 在数据服务中未定义。
  • console: "TypeError: Object # has no method 'getAllObservers' at new "
  • 我在您发布的代码 getAllObservers 函数中看不到任何地方。你能做一个 JsFiddle 吗?
  • 我的错,getAllExamples 是我要输入的。
  • @captainrad 我刚刚发布了一个答案,解释了我在您的代码中看到的问题。

标签: json angularjs model-view


【解决方案1】:

您的服务代码不正确。我看到以下问题:

  • 您正在创建一个无法从服务外部访问的局部变量 getAllExamples
  • 您正在使用$http 服务,但服务构造函数中未表达该依赖关系;
  • 您正在尝试从服务更新范围,但无法从那里访问。另外,$scope 变量甚至没有在服务代码中定义。

您的服务如下所示:

.service('data', function($http) {
    this.getAllExamples = function(callback) {
        $http.get("../../TestData/Examples.json")
            .success(function(data) {
                if (callback) callback(data.examples);
            });
        };
});

你的控制器代码会是这样的:

.controller('BaseCtrl', function ($scope, data) {
    data.getAllExamples(function(examples) {
        $scope.examples = examples;
    });

    $scope.showUser = function(example) {
        window.location = '#/user/' +example.size;
    };
});

您可以放弃 getAllExamples 函数中的回调并直接使用 $http.getreturned 承诺,但这有点复杂。

更新添加了Plunker 脚本来说明上面的代码。

【讨论】:

  • 我更新了帖子以包含 Plunker 脚本。它工作得很好。
【解决方案2】:

主模块定义应如下所示:

angular.module("projyApp",[/*dependencies go here*/]);

服务应该是这样的

//this use of module function retrieves the module
//Note from comments in angular doc: This documentation should warn that "angular.module('myModule', [])" always creates a new module, but "angular.module('myModule')" always retrieves an existing reference.)
angular.module('projyApp')
  .service('dataService', [/*dependencies,*/function() {
        var service = {
            examples:[],
            getAllExamples = function () {

                $http.get("../../TestData/Examples.json").success(function(returnedData){examples = returnedData});
            }
       }
       return service;
  });

控制器应如下所示:

angular.module('projyApp')
  .controller('BaseCtrl', function ($scope, dataService) {
    $scope.examples = [];

    $scope.showUser = function(example) {
        window.location = '#/user/' +example.size;
    };
    $scope.$watch(function(){return dataService.examples}, function(newVal,oldVal) {$scope.examples = newVal});

  });

你也可以添加

debugger;

只要调试面板处于打开状态 (F12),就在一行上触发 Chrome 中断(就像一个断点,但不必在运行时挖掘脚本)

【讨论】:

  • 这一行:$http.get("../../TestData/Examples.json").success(function(returnedData){examples = returnedData});给了我一个意想不到的“=”
【解决方案3】:

您应该在数据服务中使用回调而不是分配给scope。通过这样做,您可以在多个控制器中使用此功能,并将值分配给适当的scopes

数据服务

  var getAllExamples = function (callback) {

            $http.get("../../TestData/Examples.json").success(function(data) {
                if (typeof callback === "function") callback(data);
            });
   };

控制器

data.getAllExemples(function(data) {
    $scope.examples = data;
});

编辑

另一个是创建一个promise对象。

数据服务

  var getAllExamples = function () {

            return $http.get("../../TestData/Examples.json");
   };

控制器

var promise = data.getAllExemples();

promise.then(function(data) {
   $scope.examples = data;
});

编辑 2

在你的服务中,你需要返回你的函数

angular.module('projyApp')
  .service('data', function data() {
        var examples;

     return {
            getAllExamples: function () {

                 $http.get("../../TestData/Examples.json").success(...);

            }
};

  });

【讨论】:

  • 你也可以直接将 Promise 绑定到视图上,一旦 Promise 得到解决,Angular 就会自动渲染数据。
  • 控制台也为此打印“Object # has no method 'getAllObservers'”。
猜你喜欢
  • 1970-01-01
  • 2015-12-29
  • 2020-12-30
  • 1970-01-01
  • 2015-11-15
  • 2018-08-03
  • 2014-11-27
  • 1970-01-01
  • 2017-09-06
相关资源
最近更新 更多