thitami
thitami

Reputation: 838

AngularJS: Scope variable not updating in view

It seems that my view variable is not updating on the onSubmit event. I can see in console that the performed call to an API gets the correct results, but I do not display them properly.

JS

     angular.module('FooApp')
     .controller('FooListController', ['$scope', 'FooMapper', 'moment', 'APP_URL', '$location', function($scope, FooMapper, moment, APP_URL, $location) {


         $scope.submit = function (){

             var promise = FooMapper.find($scope.fooName);

             console.log('-- Search string: '+ $scope.fooName);
             $scope.isLoading = 0;
             promise.then(function(foo){

                 console.log('New Promise foo: ', foo);
                 $scope.fooResults = foo;

             })
         } // end of anonymous function

}
]);

HTML

<div ng-include="APP_URL + '/view/fooResolver/searchForm.html'" ng-controller="FooListController">   </div>
    <div ng-if="!isLoading" class="row">

        <div ng-if="!fooResults" class="col-md-12">
            <div class="alert alert-warning">
                No foos found.
            </div>
        </div>

        <div ng-if="fooResults" class="col-md-12">

                        <tr ng-repeat="foo in fooResults" class="active">

                            <td>
                                {{foo.id}}
                            </td>
                            <td>
                                <b>{{foo.name}}</b>
                            </td>
                            <td>
                                {{foo.country}}
                            </td>
    ....

I have also tried with $scope.$apply() but still getting the same result. Is there any chance that I have more than one scopes around?

Thank you.

Upvotes: 1

Views: 2598

Answers (1)

Sunil D.
Sunil D.

Reputation: 18193

@Mohammad Sepahvand is correct about the new scopes created by using ng-if and ng-include, however, I would recommend you avoid using $parent. I think this can create code that is brittle and harder to maintain.

Child scopes inherit properties from parent scopes through prototypical inheritance. The "old" Angular saying about "putting a dot in your model" suggests you do something like this in the parent scope (in your controller):

$scope.model = { fooModel: null };

This declares a model object that will survive prototypical inheritance. Without having a "dot in your model" the properties of the child scopes will shadow the values in the parent scope.

When your $promise is resolved, you then set a new value on $scope.model.fooModel.

While this is effectively the same thing as using $parent.fooModel, using $parent means you're depending on this parent child relationship (it makes me feel dirty). What happens if you refactor the HTML view later resulting in more/less parent/child relationships?

Upvotes: 1

Related Questions