Search code examples
javascriptangularjsangularjs-controllerangularjs-ng-optionsangularjs-controlleras

Using ng-options for select when using as notation for controller


I have a select using ng-options to define the options which works fine when I use just the controller name within the ng-controller directive. The problem is that when I add "as options" to the ng-controller it no longer works (no options).

Doesn't work:

<div ng-controller="optionsCtrl as options">
    <select ng-model="options.oxygenSource" ng-options="item.name for item in options.oxygenSources"></select><br />
</div>

Works:

<div ng-controller="optionsCtrl">
    <select ng-model="oxygenSource" ng-options="item.name for item in oxygenSources"></select>
</div>

Here's my controller if it helps:

.controller('optionsCtrl', ['$scope', 'adminServ', function ($scope, adminServ) {
    // User selections
    $scope.oxygenSource = null;

    $scope.oxygenSources = adminServ.getOxygenSources();
}])

Any thoughts? Thanks, Jason


Solution

  • You should change the controller when you are using controllerAs syntax. Controller should use this keyword instead of $scope.

    Controller

    .controller('optionsCtrl', ['$scope', 'adminServ', function ($scope, adminServ) {
        var options = this;
        options.oxygenSource = null;
        options.oxygenSources = adminServ.getOxygenSources();
    }])
    

    ControllerAs article for info by Todd motto