AngularJS Ng-model is invalid in ng-if.

Source: Internet
Author: User

Refer to the original stackflow.

Problem:

This is the fiddle showing the problem. http://jsfiddle.net/Erk4V/1/

It appears if I had an ng-model inside of a ng-if, the model does not work as expected.

I am wondering if this is a bug or if I am misunderstanding the proper usage.

<div ng-app >    <div ng-controller="main">        Test A: {{testa}}<br />        Test B: {{testb}}<br />        Test C: {{testc}}<br />        <div>            testa (without ng-if): <input type="checkbox" ng-model="testa" />        </div>        <div ng-if="!testa">            testb (with ng-if): <input type="checkbox" ng-model="testb" />        </div>        <div ng-if="!someothervar">            testc (with ng-if): <input type="checkbox" ng-model="testc" />        </div>    </div></div>

回答:

ng-ifthe directive, like other directives creates a child scope. See this fiddle:http://jsfiddle.net/erk4v/4/

So, your checkboxes changes testb the inside of the child scope, and not the outer parent scope.

Note, if you want to modify the data in the parent scope, you'll need to modify the internal properties of an object Like in the last Div, that I added.

Personal explanation: Ng-if inside will generate a subdomain, want Ng-model to take effect, need to create a sub-object in $scope, just line, such as $scope.obj, and then bind Ng-model to obj

Using Ng-show (or ng-hide) can solve this problem indirectly.

 

AngularJS Ng-model is invalid in ng-if.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.