Custom directive models do not work in ng-switch

♀尐吖头ヾ 提交于 2019-12-07 11:43:50

问题


I am trying to use AngularJS to provide a toggable dropdown list, where the selection of various options will trigger different lists. ng-switch seemed like the right way to do it, but my ng-model is not binding while inside the ng-switch. The binding works fine if I do not use ng-switch, but I do not know how to toggle my dropdown lists if that's the case. What could be the issue 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>"
    }
});

回答1:


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

This question has a lot more detail on what's going on behind the scenes and you can check out the Angular Batarang Chrome Extension to visually see the various scopes at play.

You can get around it by binding to an object value like in this updated fiddle. The main changes are:

1) Change periodModel to an object and set a property (in this example it's 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)


来源:https://stackoverflow.com/questions/16909158/custom-directive-models-do-not-work-in-ng-switch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!