如题,自己写了两个指令,想作用在同意元素下,先进行repeat,后进行bind,但目前,仅第一个执行bind

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>angular</title>
<script src="http://cdn.bootcss.com/angular.js/1.2.10/angular.min.js"></script>
</head>
<body ng-app="app">
<div ng-controller="test">
<input type="text" ng-model="msg">
<div lxc-bind="msg" lxc-reapeat="3">123123</div>
<!-- <div lxc-reapeat="3">lxc</div> -->
</div>
<script>
angular.module('app',[])
.controller('test',function($scope){
$scope.msg = 'test';
})
.directive('lxcBind',function(){
// Runs during compile
return {
restrict: 'A', // E = Element, A = Attribute, C = Class, M = Comment
link: function($scope, iElm, iAttrs, controller) {
$scope.$watch(iAttrs.lxcBind,function(newValue){
iElm.text(newValue);
})
}
};
})
.directive('lxcReapeat',function(){
return {
restrict:'A',
priority: 1000,
link:function($scope,$elm,$attr){
var repeatNum = $attr.lxcReapeat;
for (var i=repeatNum-2;i>= 0;i--){
var dom = $elm.clone();
$elm.after(dom);
}
}
}
})
</script>
</body>
</html>Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
第一点,clone方法只是克隆节点,绑定的事件是不会被克隆的。
第二点,动态添加节点到文档,angular 指令是不会生效的,需要动态编译。
angular.module('app',[]) // 注入 $compile 服务,用来动态编译 .directive('lxcReapeat',function($compile){ return { restrict:'A', priority: 1000, link:function($scope,$elm,$attr){ var repeatNum = $attr.lxcReapeat; for (var i=repeatNum-2;i>= 0;i--){ var dom = $elm.clone(); // 删除 lxc-reapeat 属性,否则动态编译会造成死循环。理解这点很重要 dom.removeAttr('lxc-reapeat'); // 动态编译并连接到scope var ele = $compile(dom)($scope); $elm.after(ele); } } } })效果图:
与ng-repeat
上面这种实现,功能上没有问题,但是阵型并不是很统一。于是,稍作修改
最终对比