2015-11-04 81 views
1

我试图使用angular-ui路由器,并不明白为什么controllerAs不起作用。当我使用$scope时,模板中的数据可用,但更改为controllerAs:'vm'会导致模板中出现空对象。不知道我错过了什么。角UI路由器控制器作为tempate中的空对象

$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> 

回答

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

+0

噢,人的工作!谢谢,这就是我匆忙复制粘贴的原因。 – neridaj

+0

很高兴看到,先生;)享受强大的UI路由器! –