1

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>

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Aww, man! Thanks, that's what I get for copy paste in a hurry.
Great to see that, sir ;) Enjoy mighty UI-Router!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.