angularjs - Why isn't my directive's selection being bound to the controller? -
i've got simple directive i'm working - it's small wrapper around dropdown. want expose attribute, "selectedoption" (well, selected-option) can two-way bind controller. i've set property in scope of directive (and set = thought allow two-way binding), exposed property on main controller.
i've attached example. have expected default item shown "beta". , if changed selections alpha, controller value updated "a". doesn't happen - appear isolated though i've specified property should available controller.
what magic bit of code missing here?
angular .module('app', []); angular.module('app').controller('test', function(){ var vm = this; vm.inv = 'b'; vm.displayinv = function () { alert('inv:' + vm.inv); }; }); angular.module('app') .directive('inventorytest', function () { return { restrict: 'e', template: '<select ng-model="ctrl.selectedoption" ng-options="inv.code inv.desc inv in ctrl.invtypes"></select>{{ctrl.sample}}. selected: {{ctrl.selectedoption}}', scope: { selectedoption: '='}, controller: function () { this.invtypes = [ { code: 'a', desc: 'alpha' }, { code: 'b', desc: 'bravo' }, { code: 'c', desc: 'charlie' }, ]; this.sample = 'hello'; }, controlleras: 'ctrl' } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.js"></script> <div ng-app="app" ng-controller="test vm"> <inventorytest selected-option='vm.inv'></inventorytest> <button ng-click="vm.displayinv()">display</button> <br/> controller: {{vm.inv}} </div>
by default, angular creates scope
object (most commonly referred variable $scope
) each html template.
the scope: { selectedoption: '='},
in code creating isolated scope directive, , making selectedoption
property on scope
object.
the line controlleras: 'ctrl'
creating property on same scope
object points controller object.
this means in controller, technically access ctrl.$parent.selectedoption
, return selectedoption
property of ctrl
object's parent, scope
. in practice, however, cumbersome.
in angular 1.3, new option added, bindtocontroller : true
. option automatically binds properties scope:
definition controlleras:
object instead of scope
itself.
Comments
Post a Comment