user1765862
user1765862

Reputation: 14145

ng-include doesn't render partial view everytime using $scope

inside view I'm conditionally rendering html using ng-include and ng-if

 <div ng-controller="myController">
        <div ng-if="myProperty == 1">
            <div ng-include="'view1.html'"></div>
        </div>
        <div ng-if="myProperty == 2">
            <div ng-include="'view2.html'"></div>
        </div>
 </div>

and inside controller I have $scope.myProperty which receive value inside controller using $scope injection from other js object. On this controller I have also callback function which updates $scope.myProperty every x seconds.

app.controller('myController', function ($scope) {
   ...
        $scope.myProperty = 0; //init value
        function callback() {
            $scope.$apply(); // force update view
            // correctly write myProperty value on every data change
            console.log($scope.myProperty); 
        }
    var otherJsObject= new myObject($scope, callback);
    otherJsObject.work();
   ...
}

callback function correctly change myProperty value but it doesn't update inside view every time.

update: $scope.bindUIProp = { a: $scope.myProperty};

    function callback() {
        $scope.$apply(); 
        $scope.bindUIProp.a = $scope.myProperty;            
        console.log('Callback  ' + $scope.myProperty);
        console.log('drawstage  ' + $scope.bindUIProp.a);

    }

    var otherJsObject= new myObject($scope, callback);
    otherJsObject.work();

and inside view I used object property

<div ng-controller="myController">
            <div ng-if="bindUIProp.a == 1">
                <div ng-include="'view1.html'"></div>
            </div>
            <div ng-if="bindUIProp.a == 2">
                <div ng-include="'view2.html'"></div>
            </div>
     </div>

this approach work every time when page is refreshed, parial view is not updated from view1 to view2 when scope.bindUIProp.a is changed to 2.

Upvotes: 0

Views: 289

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Both ng-if and ng-include create child scopes.

You are having problems due to using a primitive in your main scope. Primitives don't have inheritance so the binding is getting broken in the nested child scopes.

change it to an object:

$scope.myProperty = { someProp: 0};

Personally I rarely use ng-include because of the child scope it creates. I prefer having my own directive if all I want is to include a template.

Upvotes: 1

Jay Jay Jay
Jay Jay Jay

Reputation: 1990

Instead of writing to property at root level. Write one level below.

Instead of $scope.myProperty,

use $scope.mp.myProperty

Upvotes: 1

Related Questions