2016-08-02 52 views
1

大家好我有NG1的一些問題,這個鏈接功能無法捕捉到li如何使用angular1.x鏈接功能

var a=document.querySelectorAll(".carousel ul"); 
console.log(a); 

是輸出"[ul]"

var b=document.querySelectorAll(".carousel ul li"); 
console.log(b) 

是輸出「[]」爲什麼鏈接無法捕捉到.carousel ul li

<html lang="en" ng-app="myApp"> 
<head> 
    <meta charset="UTF-8"> 
    <title></title> 
    <script src="../js/angular.js"></script> 
</head> 
<body ng-controller="myController"> 
<carousel my-image="image"></carousel> 
</body> 
<style> 
    .carousel{ 
     width:300px; 
     height:200px; 
     display:block; 
     overflow:hidden;; 
    } 
    .carousel ul{ 
     position:relative; 
     left:0; 
     list-style:none; 
     padding:0; 
     margin:0; 
     width:900px; 
     height:100%; 
    } 
    .carousel ul li { 
     float:left; 
     width:300px; 
     height:200px; 

    } 
</style> 
<script> 
    angular.module("myApp",[]) 
      .controller("myController",function($scope){ 
       $scope.image=[ 
        {'title':"1",'img':"../image/a.jpg"}, 
        {'title':"2",'img':"../image/g.jpg"}, 
        {'title':"3",'img':"../image/z.jpg"} 
       ]; 
      }) 
      .directive("carousel",function(){ 
       return { 
        replace: true, 
        restrict: "EA", 
        scope: { 
         img: "=myImage" 
        }, 
        transclude: true, 
        template: '<div class="carousel"> <ul> <li ng-repeat="i in img"> <img width="100%" height="100%" src="{{i.img}}" alt=""/> </li> </ul> </div>', 
        link: function (scope, elem, attr) { 
         var a=document.querySelectorAll(".carousel ul"); 
         console.log(a); 
         var b=document.querySelectorAll(".carousel ul li"); 
         console.log(b); 
        } 
       } 
      }); 
</script> 
</html> 
+0

刪除'replace:true'並嘗試使用'elem'來查找子元素 – Phil

+0

var i = elem.find(「ul li」);的console.log(ⅰ);李是[]! –

回答

1

不能捕捉li因素,因爲通過你的鏈接函數被調用時,角度沒有完成DOM的操縱呢。 'ng-repeat'中的內容未被正確操作。

嘗試把它放在scope.$evalAsync

link: function (scope, elem, attr) { 
         //... 
         scope.$evalAsync(function(){ 
          var b=document.querySelectorAll(".carousel ul li"); 
          console.log(b); 
         }) 

       } 

UPDATE:

對不起$ evalAsync不要在這種情況下工作。應該使用$超時代替。

.directive("carousel",function($timeout){ 
       return { 
        replace: true, 
        restrict: "EA", 
        scope: { 
         img: "=myImage" 
        }, 
        transclude: true, 
        template: '<div class="carousel"> <ul> <li ng-repeat="i in img"> <img width="100%" height="100%" src="{{i.img}}" alt=""/> </li> </ul> </div>', 
        link: function (scope, elem, attr) { 
         var a=document.querySelectorAll(".carousel ul"); 
         console.log(a); 
         $timeout(function(){ 
          var b=document.querySelectorAll(".carousel ul li"); 
          console.log(b); 
         },0) 

        } 
       } 
      }); 
+0

它不工作李是[] –

+0

謝謝你是工作! –