Search code examples
angularjsangular-ng-if

ng-if change value in view


I'm new in angularJS, here is my issue: I would like to know what is the syntax for doing this: i would like to put the value to '0' if user.fields[5].value=undefined I tried this with ng-if but it's not working, i don't know the syntax and i don't know if ng-if is appropriate for doing this. Maybe ng-init is better, i don't know can you help me pls ?

Here is my code:

ng-if="user.fields[5].value==undefined[user.fields[5].value='0']">{{user.fields[5].value}} 

Solution

  • You can do this like that :

    This should work even though i won't advise it :

    <div ng-if="user.fields[5].value==undefined">
       <div ng-init="user.fields[5].value='0'">{{user.fields[5].value}}</div>
    </div>
    

    The proper way to do this is in the controller using $watch :

    $scope.$watch(function(){return user.fields[5];}, function(newValue){
       if(newValue===undefined){
           user.fields[5].value='0';
       }
    });
    

    But how are you getting the undefined in that field ? You shouldn't need that

    EDIT : About your comment with the API :

    Then you shouldn't do that in your controller neither in the view. You should do that in the service layer with something that look like :

    //service layer return the promise
    return $http.get('API...').then(function(response){
        var data = response.data;
        [.. format your data ...]
        return data;// don't forget to return it so your controller will have those formatted data : 
    });
    //controller layer
    myService.getData().then(function(data){
        // CLEAN data!!!!
    });