Custom directory models do not work in ng switch

I am trying to use AngularJS to provide a toggable dropdown, where selecting different options brings up different lists. ng-switch seemed like the right way to do this, but my ng-model is optional if inside ng-switch . Binding works fine if I don't use ng-switch , but I don't know how to switch my dropdowns if that happens. What could be the problem here?

jsFiddle: http://jsfiddle.net/tanweihao88/LUzXT/3/

HTML:

 <select ng-model="periodRangeModel" ng-options="item for item in items"></select> <div ng-switch on="periodRangeModel"> <span ng-switch-when="Month"><period-selector items="monthOptions" ng-model="periodModel"></period-selector></span> <span ng-switch-when="Quarter"><period-selector items="quarterOptions" ng-model="periodModel"></period-selector></span> <br> </div> 

JS:

 angular.module('myApp', []) .controller("MyCtrl", function($scope) { $scope.items = ['Month', 'Quarter']; $scope.periodRangeModel = "Month"; $scope.quarterOptions = ["Jan-Mar", "Apr-Jun", "Jul-Sept", "Oct-Dec"]; $scope.monthOptions = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; $scope.periodModel = $scope.monthOptions[0]; }) .directive('periodSelector', function() { return { restrict: 'E', replace: true, scope: { items: '=', ngModel: '='}, template: "<span><select ng-options='period for period in items' ng-model='ngModel'></select></span>" } }); 
+4
source share
1 answer

The main reason the binding does not work as intended is that ng-switch creates a new scope and when binding to the string primitive, the original periodModel not updated as you expect (since the new periodModel updated).

This question contains a lot more information about what is going on behind the scenes, and you can check the Angular Chrome Batarang Extension to visually see the different playback areas.

You can bypass it by binding to the value of the object, for example, in this updated script . Major changes:

1) Change periodModel to an object and set the property (in this example it is called value )

 $scope.periodModel = { value: $scope.monthOptions[0] }; 

2) Change any binding code to access periodModel.value instead of periodModel

 <period-selector items="monthOptions" ng-model="periodModel.value"></period-selector> Model: {{periodModel.value}} (this is supposed to change) 
+6
source

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


All Articles