我的指令需要在其模板中选择两个部分模板:
<div ng-if="enablerowselection" ui-grid="gridOptions" ui-grid-pagination ui-grid-selection class="grid"></div>
<div ng-if="!enablerowselection" ui-grid="gridOptions" ui-grid-pagination class="grid"></div>
在我的指令的链接器函数中,我从属性中获取了enablerowselection的值:
function linker(scope, element, attrs) {
scope.enablerowselection = attrs.enablerowselection; //enablerowselection is an attribute for my directive
}
但是,这会导致以下错误:
Error: [$compile:nonassign]
我想我需要在指令中编译部分模板,所以我将以下内容添加到链接器函数中,但它仍然不起作用:
$compile(element.contents())(scope);
编辑:以下是我的指令代码:
angular.module('myApp')
.directive('myDirective', myDirective);
myDirective.$inject = ['$compile'];
function myDirective($compile) {
return {
restrict: 'EA',
scope: {
enablerowselection: '='
},
templateUrl: '/path/to/directive_tmpl.html',
link: linkerFn
};
function linkerFn(scope, element, attrs) {
$scope.enablerowselection = attrs.enablerowselection;
$compile(element.contents())(scope); //does not help
} //linkerFn
}
答案 0 :(得分:1)
当我看到enablerowselection
与隔离范围一样时,你应该在你的指令中使用make that属性作为可选项,这样如果没有提供,那么指令就不会抛出错误。您可以使用=?
对该变量进行隔离的范围属性,如
scope: {
enablerowselection: '=?'
},
如果您在指令中需要该值,则应将其作为属性添加到指令元素
中<my-directive enablerowselection="enablerowselection"></my-directive>
基本上你应该在该属性中添加范围变量,当你使用=
链接功能
function linkerFn(scope, element, attrs) {
//scope.enablerowselection = attrs.enablerowselection; //reomve this
//you already have value in `$scope.enablerowselection`,
//you don't need to get it from attribute,
//'=' in isolated scope means value of parent scope variable specified in attribute,
//gets available inside the isolated scope(basically its two way binded.)
$compile(element.contents())(scope); //does not help
}