2015-11-04 77 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路由器! –