Angular UI-Router controller作为tempate中的空对象

时间:2015-11-04 18:56:47

标签: angularjs angular-ui-router

我正在尝试使用angular-ui-router而不理解为什么controllerAs无效。当我使用$scope时,模板中的数据可用,但更改为controllerAs:'vm'会导致模板中出现空对象。不确定我错过了什么。

$stateProvider
    .state('myState', {
        url: '/my-state',
        templateUrl: 'app/myState/myState.html',
        controller: 'myStateController',
        controllerAs: 'vm'
    });

function myStateController(myStateFactory, $scope) {

    var vm = this;
    vm.test = "hello";

    return myStateFactory.getCountriesStates()
    .then(function (response) {
        vm.countriesStates = response.Countries;
    });
} 

模板:

<div class="col-md-9">
{{vm.test}} <!-- empty-->
    <select ng-model="selectedCountry" class="form-control" ng-change="">
        <option value="">Select a country</option>
        <option ng-repeat="country in vm.countriesStates" 
                value="{{country.v}}">{{country.n}}</option> <!-- empty -->  
    </select>
</div>

1 个答案:

答案 0 :(得分:2)

a working plunker

重点是 - 冗余返回声明

这个棘手的工厂:

.factory('myStateFactory', ['$timeout', function($timeout) {
    return {
      getCountriesStates: function() {
        return $timeout(function(){
          return {
            Countries: [{ v: "x", n: "Czech" }, { v: "o", n: "Other"}]
          };
        })
      }
    }
  }])

如果我们跳过返回

,此控制器是按预期工作的
function myStateController(myStateFactory, $scope) {
  var vm = this;
  vm.test = "hello";

  // do not use return
  //return myStateFactory.getCountriesStates()
  myStateFactory.getCountriesStates()
    .then(function(response) {
      vm.countriesStates = response.Countries;
    });
}
myStateController.$inject = ['myStateFactory', '$scope']

action here

中查看