![](/img/trans.png)
[英]How to access elements attributes from custom directive while keeping access to parent scope?
[英]AngularJS Custom Directive Access attributes in Template while inheriting parent scope
我有一个自定义指令,我想继承父作用域。 我还想通过属性传递一个值。 它看起来像这样:
调节器
app.controller('Main', ['$scope', function($scope){
$scope.cols = { 'col1': true, 'col2':false, 'col3': true};
$scope.toggleCol = function(colName){
$scope.cols[colName] = !$scope.cols[colName];
};
}]);
指示
wrApp.directive("custTh", function(){
return {
restrict: "EA",
scope: false,
replace: true,
template: '<th ng-show="cols[{{ colname }}]" ng-click="toggleCol({{ colname }})">{{ colname }}</th>',
};
});
HTML
<th cust-th colname="col2"></th>
我似乎无法访问属性值bc我继承父范围。 是否可以直接从模板访问指令属性?
只要您不在指令中声明隔离范围,就可以访问父范围:
<-- cust-th template can access Main controller's scope -->
<div ng-controller="Main">
<th cust-th></th>
</div>
您的代码中只有一些语法错误阻止您执行此操作。 在模板中,您不需要插入传递给angular指令的值(ng-click和ng-show):
<th ng-show="cols[colname]" ng-click="toggleCol(colname)">{{ colname }}</th>
colname尚未在控制器中声明为范围变量,因此当Angular编译HTML时,它将无法识别它。 如果您希望继续将其作为HTML元素的属性传递,则需要在指令中创建一个angular元素,以便使用链接函数访问该值(请参阅https://docs.angularjs.org/指导/指示 )。 如果你想使用插值({{colname}}),那么你需要在你的控制器中有一个变量
$scope.colname = 'col1';
否。继承父作用域时,无法访问指令属性。 要做到这一点,你必须创建指令自己的范围,如下所示:
app.directive("custTh", function(){
return {
restrict: "EA",
scope: { colname: '@'},
template: 'Name : {{ colname }}',
};
});
在你的HTML remplate你必须这样写:
<div ng-controller="Main">
<cust-th colname="col2" ></cust-th>
</div>
我也为你提供了帮助。 我觉得这很有用,请接受这个作为答案。
您可以继承范围,但也可以使用以下命令创建子范围:
scope: true
然后为了传递值:
link: function(scope, element, attrs) {
scope.$watch(attrs.valueFromOutside, function(newValue) {
scope.valueFromOutside = newValue;
});
}
这种方式在指令的内部范围内,您可以拥有不同的值,同时仍然可以访问父作用域。
你可以在这里看到一切: http : //jsfiddle.net/HB7LU/15120/
模板可以是字符串或函数:
模板
可能的HTML标记:
替换指令元素的内容(默认)。 替换指令的元素本身(如果replace为true - DEPRECATED)。 包装指令元素的内容(如果transclude为true)。 价值可能是:
一个字符串。 例如
<div red-on-hover>{{delete_str}}</div>
。 一个函数,它接受两个参数tElement和tAttrs(在下面的编译函数api中描述)并返回一个字符串值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.