mahendrakawde
mahendrakawde

Reputation: 215

Angularjs ng-if not working with ng-model

I am using angularjs to integrate my api.

I am facing problem with using ng-if inside textbox.

so below is my snippet of HTML code:

<input type="text" value="" data-ng-if="edit" ng-model="name">
<input type="text" value="" data-ng-if="!edit" ng-model="singleAppDetails.name">

Here edit variable is there in scope that is in my controller i have declared it like this:

$scope.edit = false;

So if edit is false it should get bind with ng-model="name" and if edit is true it should get bind with ng-model="singleAppDetails.name" But it is not binding it as expected.

Further I am using $http.post to post the data to server like below:

 $scope.addApp = function(){    
       $scope.apps = []; 
        $scope.apps.push({'name':$scope.name, 'domain':$scope.domain, 'appId':$scope.appId, 'secret':$scope.secret});
        // Writing it to the server
        //      
        var dataObj = {
                name : $scope.name,
                domain : $scope.domain,
                appId : $scope.appId,
                secret : $scope.secret
        };  
        var res = $http.post('http://192.168.1.30:8090/apps/', dataObj);
        res.success(function(data, status, headers, config) {
            $scope.message = data;
        });
        res.error(function(data, status, headers, config) {
            alert( "failure message: " + JSON.stringify({data: data}));
        });     
        // Making the fields empty
        //
       $scope.name='';
       $scope.domain='';
       $scope.appId = '';
       $scope.secret = '';
    };

But this always sends null data.

Upvotes: 1

Views: 3513

Answers (2)

Imal Hasaranga Perera
Imal Hasaranga Perera

Reputation: 10029

ng-if is creating a child scope because that the input elements does not see the scope variable defined in the controller you have two ways to solve this problem

  1. use an object reference ex : $scope.user = { name : "" } inside the template

    <input type="text" ng-model='user.name' />

  2. you can tell angular to look for the variable in parent scope instead child scope

    <input type="text" ng-model='$parent.name' />

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691765

ng-if has its own scope. So the name attribute that is populated by the first input is in the ng-if scope instead of being in your controller scope.

The second input should work fine, provided that your controller initializes singleAppDetails to a non-null object:

$scope.singleAppDetails = {};

Rule of thumb: always have a dot in your ng-model. Always populate objects in the scope rather than the scope itself.

Upvotes: 2

Related Questions