Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No access to scope variables directly inside ng-template

So I recently moved some repeated markup into ng-template blocks, and I noticed that inside the blocks, I do not get direct access to scope variables, but I can still call scope functions.

For instance, consider the following markup:

<script type="text/ng-template" id="toggle-button.html">
    <button ng-click="toggleFlag()">I Toggle the Flag</button>
    <button ng-click="flag = !flag">I Do Nothing</button>
</script>
<span ng-include="'toggle-button.html'"></span>
The flag is {{flag}}

Paired with the following script:

var app = angular.module('myApp', [])
.controller("myController", ['$scope', function($scope){
    $scope.flag = true;

    $scope.toggleFlag = function(){
        $scope.flag = !$scope.flag;
    }
}])

Live JS Fiddle of this behavior: http://jsfiddle.net/uM4Ss/

The first button works, the second does not. Can somebody please answer why this is the case?

like image 982
StephenRios Avatar asked Apr 15 '14 18:04

StephenRios


2 Answers

ngInclude creates new child scope.

You should use $parent if you want to access parent scope variables. http://jsfiddle.net/mX7v2/

Also you can define controller inside template to share the same scope between controller and a template.

like image 158
SlyChan Avatar answered Oct 27 '22 05:10

SlyChan


You are binding to a primitive. Bind to an object instead, and the binding will work in the child scope: http://jsfiddle.net/wittwerj/uM4Ss/2/

<script type="text/ng-template" id="toggle-button.html">
    <button ng-click="toggleFlag()">I Toggle the Flag</button>
    <button ng-click="flags.flag = !flags.flag">I Do Nothing</button>
</script>
<span ng-include="'toggle-button.html'"></span>
The flag is {{flags.flag}}

script:

var app = angular.module('myApp', [])
.controller("myController", ['$scope', function($scope){
    $scope.flags=  {
        flag: true
    };

    $scope.toggleFlag = function(){
        $scope.flags.flag = !$scope.flags.flag;
    }
}])
like image 43
j.wittwer Avatar answered Oct 27 '22 06:10

j.wittwer