Angularjs指令隔离作用域
angularjs directive isolated scope
我有一个指令和一个控制器根据这(它来自Angular JS指令PacktPub书,主要)。
angular.module('myApp',[])
.directive('myIsolatedScopedDirective', function(){
return {
scope : {
'title' : '@msdTitle'
},
link: function ($scope, $element, $attrs) {
$scope.setDirectiveTitle = function (title) {
$scope.title = title;
};
}
};
})
.controller('MyCtrl', function($scope){
$scope.title = "Hello World";
$scope.setAppTitle = function(title){
$scope.title = title;
};
});
<div ng-controller="MyCtrl">
<h2>{{title}}</h2>
<button ng-click="setAppTitle('App 2.0')">Upgrade me!</button>
<div my-isolated-scoped-directive msd-title="I'm a directive within the app {{title}}">
<h4>{{title}}</h4>
<button ng-click="setDirectiveTitle('bob')">Bob it!</button>
</div>
</div>
问题如下:为什么<h4>{{title}}</h4>
等于"Hello World"
而不是"I'm a directive within the app Hello World"
?有人能解释一下吗?谢谢你。
恰好
原因是,您必须输入模板内部指令的template
属性,使其成为孤立的一个。现在,指令创建了一个孤立的作用域,但它不会在任何地方使用它,因为当指令的link函数被触发时,指令标签中的内容已经在父作用域(MyCtrl)中求值了
这可能是你想要做的http://plnkr.co/edit/jmWrNpLFttDPhSooPF0M?p=preview
指令
.directive('myIsolatedScopedDirective', function(){
return {
scope : {
'title' : '@msdTitle'
},
replace: true,
template: '<div><h4>{{title}}</h4>' +
'<button ng-click="setDirectiveTitle(''bob'')">Bob it!</button>',
link: function ($scope, $element, $attrs) {
$scope.setDirectiveTitle = function (title) {
$scope.title = title;
};
}
};
标记
<div my-isolated-scoped-directive msd-title="I'm a directive within the app {{title}}"></div>
相关文章:
- 从控制器继承了隔离的作用域以生成可重用的指令
- 两个指令创建新的继承的和隔离的作用域-元素得到哪个
- AngularJS指令隔离作用域
- 访问多个指令的隔离作用域
- 如何在隔离作用域指令中访问此作用域变量
- AngularJs,在没有隔离的情况下将指令属性添加到作用域
- AngularJS:ngRepeat作用域在具有隔离作用域和ngTransclude的自定义指令中失败
- 将回调绑定到没有隔离作用域的指令
- 在不使用隔离作用域的情况下执行函数的角度指令
- 隔离作用域+绑定名称和仅在AngularJS中的隔离作用域之间的差异
- ng隔离未附加到templateUrl的作用域
- 角度:覆盖'@'链接或控制器中隔离作用域中的属性
- 隔离未更新指令中值的作用域
- 使用隔离作用域的角度指令
- 在AngularJS中对指令的隔离作用域设置新属性
- 如何在使用ng repeat时停止传播(或者如何更好地隔离作用域)
- $scope变量在指令隔离作用域中未定义
- 无法从具有隔离作用域的指令中访问控制器中定义的对象
- 在指令的隔离作用域中定义的调用函数
- 试图在作用域隔离的指令中运行绑定方法