将数据从Angular服务传递到控制器和刷新视图

时间:2014-11-07 20:03:27

标签: javascript angularjs

所以我有一个引导列表:

<div class="ajax_company_list" ng-app="app">
    <div class='list-group' ng-controller="PolicyController as policyCtrl">
         <a href="#" class='list-group-item' ng-repeat="company in policyCtrl.companies">{{company.primary_name}}
         </a>               
         <div id="loadingIcon" class='list-group-item'>
              Loading...
         </div>
    </div>
</div>

这是我的Angular Javascript:

var app = angular.module('app', []);

app.controller('PolicyController', ['$scope', 'CompanyService', function($scope, CompanyService) {

    $scope.companies = [

    {
        policy_number: 12345,
        primary_name: "test"
    }

    ];

    $scope.getCompanies = function() {

        CompanyService.fetchCompanies()
            .success(function(data) {

                $scope.companies = data.companies;

            })

        }

    }]);

app.factory('CompanyService', ['$http', function($http) {

    return {

        fetchCompanies: function() {

            return $http.get('http://spoonerinc:8886//json/glmod_Spooner-Inc?pagenum=1');

        }

}

}]);

我基本上有2个问题。如果我将$ scope.companies设置为等于一个对象数组,则它不显示但如果我将$ scope.companies更改为this.companies,它将再次开始工作。这是为什么?

第二个问题,我可以看到服务调用在我的网络选项卡中运行,并且可以console.log数据,它可以正常运行。但它根本没有更新我的实际列表,我不确定我做错了什么。

我对Angular相当新,所以如果对如何更好地编写代码有任何建议,请告诉我。

谢谢!

2 个答案:

答案 0 :(得分:1)

因为您正在使用"Controller As"语法,它有效地将整个控制器对象发布到范围。

引擎盖下发生的事情看起来像这样:

function myCtrl($scope){

  $scope['someAlias'] = this;

}

如果您打算将控制器用作语法,最好使用更基于对象的方法,而不是将内容推送到$scope

原型:

function myCtrl(companiesService){
   this.companiesService = companiesService;
   this.init();
}

myCtrl.prototype = {
  init:function(){
    var _this = this;

    _this.companiesService.get()
      .then(function(result){
         _this.companies = result.data;
      });
  }
};

或作为闭包样式对象:

function myCtrl(comapniesService){
   var ctrl = {};

   function init(){
      companiesService.get()
      .then(function(result){
         ctrl.companies = result.data;
      });
   }

   return ctrl;
}

答案 1 :(得分:0)

关于你的第二个问题,我认为你的问题在这里:

ng-repeat="company in policyCtrl.companies"

您不需要将控制器指定为前缀,因为您已经使用ng-controller声明了它。它应该是:

ng-repeat="company in companies"

并且ng-controller为:

ng-controller="PolicyController"

我的猜测是,一旦你纠正了这个问题,第一个问题就会消失。