Paul D'Ambra
Paul D'Ambra

Reputation: 7814

Using ng-model entirely inside directive on <select/> doesn't create/update the model

I want to make a directive that I can insert into many pages. It will hold several form controls. When their value is changed the page will react.

So my first step was a directive which contains a select box. It's values are set by an API and that works fine but when I change the selected value the ng-model is not created on the scope.

So, I'm never seeing ng-model set. I assume I'm fangling something the wrong way but can't figure out how it should be... Which means I can't $watch its value or have an ng-change which responds to it because it doesn't exist.

Am I trying to do something impossible or just doing it the wrong way?

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

app.controller('acontroller', function($scope) {
  $scope.text = 'some text';  
});

app.directive('myDirective', function() {
  return {
            restrict: 'E',
            replace: true,
            scope: {},
            template: '<div><select ng-options="select as thing.name for thing in things track by thing.id" ng-model="selectedThing"></select><p>selected thing is {{selectedThing}}</p></div>',
            link: function (scope) {
                //imagine this comes from an API
                scope.things = [{id:1, name:'one'}, {id:2, name:'two'}];
            }
        };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>

<div ng-app="anapp" ng-controller="acontroller">
  
  <my-directive></my-directive>
  
  {{text}}
  </div>

Upvotes: 1

Views: 87

Answers (1)

ste2425
ste2425

Reputation: 4786

your ng-options string is wrong. I do not believe there is a key word select.

By the looks of it what you want is to be able to say 'select this as that'.

So that would be

//Selecting entire object
ng-options="thing as thing.name for thing in things track by thing.id"
//Selecting just id
ng-options="thing.id as thing.name for thing in things track by thing.id"

Related Docs

Upvotes: 2

Related Questions