alt*_*urt 5 angularjs angularjs-directive
我正在尝试将简单的ng-mouseover绑定添加到由指令管理的元素.但是colud没有让它运转起来.
@ http://jsbin.com/aqibij/2/edit
我在添加ng-mouseover绑定后尝试重新编译元素.指令.compile和外部控制器运行,但指令.linker不运行.
@ http://jsbin.com/ikebed/1/edit
我已将$ compile'转移到链接器中.运行正常,ng-mouseover运行正常,但在链接器中重新编译会导致无限循环,最终导致浏览器崩溃:)
如何使用指令将ng-*绑定添加到元素?我在这些方法中做错了什么?
我以为你和我在同一条船上,但也许你不是。不管怎样,这里有两个解决方案。我被困在了第二个。
如果您知道您正在处理的元素将是 div、span、h1 等 - 或者它并不重要(采用一个元素并将其替换为您需要的元素)。
<div data-mydirective>
<span>some other stuff</span>
<div>more stuff</div>
</div>
Run Code Online (Sandbox Code Playgroud)
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 ) {
}
};
}]);
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
这就是我面临的问题。基本上,如果您有一个可能位于 h1、h2、span、div、nav 等上的指令,并且您想ng-*从指令中添加 和 属性。
您不能使用 a,template因为您不知道该元素是什么。不想将 ah1替换为divright?这就是我走编译路线的原因。嗯,实际上可以是我们可以访问和template的函数。elementattrs
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 ) {
}
}
}]);
Run Code Online (Sandbox Code Playgroud)
与上面相同。div将HTML 中的元素更改为 a nav,输出将反映更改。
| 归档时间: |
|
| 查看次数: |
2014 次 |
| 最近记录: |