我正在尝试向指令管理的元素添加简单的 ng-mouseover 绑定(bind)。但是colud没有让它工作。
@ http://jsbin.com/aqibij/2/edit
添加 ng-mouseover 绑定(bind)后,我尝试重新编译元素。 directive.compile 和外部 Controller 运行,但directive.linker 不运行。
@ http://jsbin.com/ikebed/1/edit
我已将 $compile'ing 移到链接器中。它运行良好,ng-mouseover 运行良好,但在链接器中重新编译会导致无限循环,最终导致浏览器崩溃:)
如何使用指令将 ng-* 绑定(bind)添加到元素?我在这些方法中做错了什么?
最佳答案
我以为你和我在同一条船上,但也许你不是。无论哪种方式,这里有两个解决方案。我被困在第二个。
1) 特定元素指令
如果您知道您正在处理的元素将是 div、span、h1 等等 - 或者没关系(取一个元素并将其替换为您需要的元素)。
HTML
<div data-mydirective>
<span>some other stuff</span>
<div>more stuff</div>
</div>
指示
module.directive( 'mydirective', [ function() {
return {
restrict: "A",
controller: function( $scope ) {
$scope.test = function() {
console.log('howdy');
}
},
template: "<div data-ng-transclude data-ng-mouseover='test()'></div>",
transclude: true,
replace: true,
link: function ( scope, element, attrs ) {
}
};
}]);
输出
<div ng-mouseover="test()" data-ng-transclude="" data-mydirective="">
<span class="ng-scope">some other stuff</span>
<div class="ng-scope">more stuff</div>
</div>
2) 针对非特定元素的指令
这是我面临的问题。基本上,如果您有一个可能位于 h1、h2、span、div、nav 等上的指令,并且您想添加您的
ng-*
和指令中的属性。您不能使用
template
因为你不知道元素是什么。不想拍h1
并将其替换为 div
对?这就是我走编译路线的原因。好吧,template
实际上可以是一个我们可以访问的函数element
和 attrs
.指示
module.directive( 'mydirective', [ function() {
return {
restrict: "A",
controller: function( $scope ) {
$scope.test = function() {
console.log('howdy');
}
},
template: function( element, attrs ) {
var tag = element[0].nodeName;
return "<"+tag+" data-ng-transclude data-ng-mouseover='test()></"+tag+">";
},
transclude: true,
replace: true,
link: function ( scope, element, attrs ) {
}
}
}]);
HTML/输出
和上面一样。更改
div
将 HTML 中的元素转换为 nav
,并且输出将反射(reflect)更改。
关于Angularjs - 使用指令添加 ng-* 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18206809/