2013-11-01 97 views
0

我實現navigation指令,應該爲每個導航項目a元素:訪問元素指令兒童

<navigation title="My Web Page"> 
    <a href="#">Home</a> 
    <a href="#">About</a> 
</navigation> 

我怎樣才能訪問這些錨?訪問element的孩子link()只返回模板的孩子,而不是我正在尋找的'a'。

.directive('navigation', function() { 
    return { 
     template: template, 
     restrict: 'E', 
     replace: 'true', 
     scope: { 
     title: '@' 
     }, 
     link: function postLink(scope, element, attrs) { 
     // This only looks in the directive's template 
     console.log($(element).find('a'));    
     } 
    }; 
    }); 

我在想什麼?我期待着在指令的作用域中附加一組錨,並在模板中遍歷它們。

+0

看起來您忘記了在您的指令中跨越數據,只是將您的導航標記替換爲您的模板。因此,它們在鏈接功能中找不到。 – adamK

+0

ngTransclude是我一直在尋找的!你能把它作爲答案發布嗎? – jviotti

回答

2

爲了您需要使用transclude屬性的新模板內移動的原創內容。當translude設置爲true時,該指令將刪除原始內容,但也可通過ng-translude指令將其重新插入到模板中。見下面的例子。

不透露原始數據錨標記被刪除,這就是爲什麼你的鏈接功能找不到它們。

.directive('navigation', function() { 
    return { 
     template: '<div>Tansclude data here: <span ng-translude></span></div>', 
     restrict: 'E', 
     replace: true, 
     transclude: true, 
     scope: { 
      title: '@' 
     }, 
     link: function postLink(scope, element, attrs) { 
      console.log($(element).find('a'));    
     } 
    }; 
}); 
1

我有點困惑在您的資產淨值TEMS是從哪裏來的,但我給它一個去

我假設你的導航元素在一個控制器,是父母的指令定義

function myCtrl ($scope){ 
    $scope.navArray=[{title: 'Link1', href: 'www.example.com'}, {...}]; 
} 

你他們將不得不聲明數組作爲屬性在你的指令

<navigation nav="navArray"></navigation> 

,它的雙向綁定到你的指令範圍

.directive('navigation', function() { 
    return { 
     template: '<div><a ng-repeat="link in nav" href="link.href">{{link.title}}</a></div>', 
     restrict: 'E', 
     replace: 'true', 
     scope: { 
     nav: '=' 
     }, 
     link: function postLink(scope, element, attrs) { 

     } 
    }; 
    }); 

請記住,您希望在鏈接函數中遠離DOM操作。相反,我建議在您的模板中使用ng-repeat,並確保導航項的數組傳遞到您的指令的作用域。

編輯:見小提琴http://jsfiddle.net/nicolasmoise/8YQPh/3/