angular.js - angular 自定义指令 repeat bind 怎么不能同时作用在同一元素上
PHP中文网
PHP中文网 2017-05-15 17:08:02
0
1
529

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

<!DOCTYPE html>
<html lang="zh-cn">
<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">
    <p ng-controller="test">
            <input type="text" ng-model="msg">
            <p lxc-bind="msg" lxc-reapeat="3">123123</p>
            <!-- <p lxc-reapeat="3">lxc</p> -->
    </p>
    <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>
PHP中文网
PHP中文网

认证高级PHP讲师

모든 응답(1)
迷茫

첫 번째 요점은 clone 메서드는 노드만 복제하고 바인딩된 이벤트는 복제되지 않습니다.
두 번째 요점은 문서에 노드를 동적으로 추가할 때 각도 지시문이 적용되지 않으며 동적 컴파일이 필요하다는 것입니다. 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

上面这种实现,功能上没有问题,但是阵型并不是很统一。于是,稍作修改

<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>angular</title>
    <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> 
</head>
<body ng-app="app">
    <p ng-controller="test">
        <p ng-repeat="i in [1,2,3]">{{i}}</p>
        <input type="text" ng-model="msg">
        <p lxc-bind="msg" lxc-reapeat="3">123123</p>
    </p>
    <script>
        angular.module('app',[])
        .controller('test',function($scope){
            $scope.msg = 'test';
        })
        .directive('lxcBind',function(){
            return {
                restrict: 'A',
                link: function($scope, iElm, iAttrs, controller) {
                    console.log(2)
                    $scope.$watch(iAttrs.lxcBind,function(newValue){
                        iElm.text(newValue);
                    })
                }
            };
        })
        .directive('lxcReapeat',function($compile){
            return {
                restrict:'A',
                priority: 1000,
                link: function(scope, iElement, iAttrs, controller){
                    
                    var repeatNum = iAttrs.lxcReapeat,
                        $parent = iElement.parent(),
                        html = '';

                    iElement.remove();

                    for (var i = 0; i < repeatNum; i++){
                        if( i == 0 ){
                            html = '<!-- lxcReapeat: '+repeatNum+' -->';
                        }else{
                            html = '<!-- end lxcReapeat: '+repeatNum+' -->';
                        }
                        var dom = iElement.clone()[0];
                        dom.removeAttribute('lxc-reapeat');
                        dom = $compile(html+dom.outerHTML)(scope);
                        $parent.append(dom);
                        dom.attr('lxc-reapeat', repeatNum).addClass('lxc-bind');
                    }

                    $parent.append(html);
                    
                }
            }
        })
    </script>
</body>
</html>

最终对比

请采纳 으아악

렌더링:
🎜 🎜🎜 🎜ng-repeat
🎜 🎜위 구현은 기능적인 문제는 없으나, 형태가 그다지 균일하지 않습니다. 그래서 살짝 수정했어요🎜 으아악 🎜최종 비교
스팬>🎜 🎜입양해주세요. 🎜
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!