neridaj
neridaj

Reputation: 2193

Angular UI-Router controllerAs empty object in tempate

I'm trying to use angular-ui-router and dont understand why controllerAs isn't working. When I use $scope the data is available in the template but changing to controllerAs: 'vm' results in an empty object in the template. Not sure what I'm missing.

$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;
    });
} 

the template:

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

Upvotes: 1

Views: 172

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

There is a working plunker

The point is - redundant return statement

with this tricky factory:

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

is this controller working as expected, if we skip return

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']

Check it in action here

Upvotes: 2

Related Questions