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?
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.
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;
}
}])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With