Why is my control selection not related to the controller?

I have a very simple directive that I work with - this is a small cover around the drop-down list. I want to set the "selectedOption" attribute (well, the selected option) from it, which I can bind to the controller from two sides. I set the property to the scope of the directive (and set it =, which I thought a two-way binding would allow), then set the property on the main controller.

I gave an example. I would suggest that the default item shown is "Beta." And if I changed the selection to Alpha, the controller value would be updated to "A". But this does not happen - they seem to be isolated, although I indicated that this property should be available to the controller.

What magic bit of code am I missing?

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 as inv.desc for 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 as vm"> <inventorytest selected-option='vm.inv'></inventorytest> <button ng-click="vm.displayInv()">Display</button> <br/> Controller: {{vm.inv}} </div> 
+3
source share
1 answer

By default, Angular creates a scope object (most commonly referred to as the $scope variable) for each HTML template.

scope: { selectedOption: '='}, in your code, it actually creates a scope isolated for the directive and makes the selectedOption property for this scope object.

The controllerAs: 'ctrl' creates a property for the same scope object that points to the controller object.

This actually means that in the controller you could technically access ctrl.$parent.selectedOption , which will return the selectedOption property of the parent ctrl object, which is equal to scope . In practice, however, this is very cumbersome.

Angular 1.3 adds the new bindToController : true option bindToController : true . This parameter automatically binds the properties from the scope: definition to the controllerAs: object instead of scope .

+2
source

Source: https://habr.com/ru/post/1235130/


All Articles