Why doesn't this angular select wrapper directive work?

Im trying to make a directive that wraps around select with a hard-coded list

var app = angular.module('dirApp',[]);

app.directive('dir', [function(){
  return{
            restrict: 'E',
            template: "<select ng-options='x for x in vm.arr'></select>",
            controllerAs: 'vm',
            link: function(scope) {
                scope.arr=["a", "b"];
            }
        };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="dirApp">
<dir></dir>
  </div>

As you can see for some reason the list does not get populated with values. What am I doing wrong?

Upvotes: 0

Views: 184

Answers (2)

bosch
bosch

Reputation: 1129

You forgot to specify ng-model="currentValue" in your select; without it the options will not initialize. Also, you may want to define the controller if you want to reference it with controllerAs:

controller: function () {
        this.arr = ["a", "b"];
    },

or you can put your array directly in the scope of your directive. Here's a little update for your directive:

myApp.directive('dir', function () {
return {
    restrict: 'E',
    template: "<select ng-model='crrValue' ng-options='x for x in vm.arr'></select><div ng-repeat='item in arr'>{{item}}</div>",
    controller: function () {
        this.arr = ["a", "b"];
    },
    controllerAs: 'vm',
    link: function (scope) {
        scope.arr = ["c", "d"]
    }
};
});

You will notice the difference between the div and the select.

Hope this helps anyone!

Upvotes: 0

Paul Boutes
Paul Boutes

Reputation: 3315

You have to put your data into your Controller, and add an ngModel to your template.

Directive

(function(){

  function dir() {
      return{
          restrict: 'E',
          template: "<select ng-model='vm.x' ng-options='x for x in vm.arr'></select>",
          controllerAs: 'vm',
          controller: function() {
            var vm = this;
            vm.arr = ["a", "b"];
            vm.x = vm.arr[0]
          }
        };
  }

angular
  .module('app')
  .directive('dir', dir);


})();

Upvotes: 2

Related Questions