Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

angularjs - ng-switch does not bind ng-model

I have this repro http://embed.plnkr.co/nVCmukG5abpi1Y4ZHkrq that show when I click 'Title3' and enter a value in text box although the entered value shows reflected in the UI, when I click the 'click' button nothing is binded for the scope attribute $scope.test.

I don't know what is wrong with ng-switch or maybe I'm doing something wrong. Help is appreciated!!!

http://embed.plnkr.co/nVCmukG5abpi1Y4ZHkrq

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is a scope inheritance problem due to ng-switch creating its own scope.

One recommendation made often is always to use a dot on models. The reason is that when the controller scope item is an object and not a primitive, sub scopes will create a reference to the initial object. If model is a primitive it will not update the original.

For example:

<input ng-model="test.value" placeholder="pre" type="text" />
$scope.test={value:''}

Another approach is to use $parent in html model markup:

<input ng-model="$parent.test" placeholder="pre" type="text" />

Using the dot methodology is a good practice to avoid these issues as you don't need to think about deeper nested scopes.

Demo using test.value as model: http://plnkr.co/edit/CkiF55bLXsYzR6ZjcrJp?p=preview

Reference regarding dot in models(valuable reading): https://github.com/angular/angular.js/wiki/Understanding-Scopes


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...