2013-10-28 40 views
0

請原諒我缺乏理解。如何將集合傳遞給angular.js中的指令?

我通過集合的名字我的指令:

<ul tag-it tag-src="preview_data.preview.extract.keywords"><li>Tag 1</li><li>Tag 2</li></ul> 

該指令規定:

app.directive('tagIt', function(){ 
    return { 
     restrict: 'A', 
     link: function(scope,elem, attr) { 

      elem.tagit(); 
      console.log(attr.tagSrc); //the name of my collection, but how do I access it? 
     } 
    } 
}); 

如何從指令訪問我的收集,並確保我的指令被稱爲當收集是填充?這裏是how preview_data.preview.extract.keyword s得到填充。

app.config(function ($routeProvider, $locationProvider) { 
    $locationProvider.html5Mode(true); 
    console.log('config'); 
    $routeProvider.when("/", { 
     templateUrl: "/templates/addItem.html", 
     controller: "AddItemController", 
     resolve: { 
      loadData: addItemCtrl.loadData 

     } 
    }); 
}); 

var addItemCtrl=app.controller("AddItemController", function ($scope, $route, $sce, Preview) { 
    var title = decodeURIComponent($route.current.params.title); 
    var ua = decodeURIComponent($route.current.params.ua); 
    var uri = decodeURIComponent($route.current.params.uri); 
    $scope.preview_data = { 
     uri: uri, 
     title: title, 
     ua: ua 
    } 
    //pass parameters to web preview API 

    Preview.get(uri, ua, title).then(function (data) { 

     $scope.preview_data.preview = data; 
     if (data.embed.html) { 
      $scope.preview_data.preview.embed.html = $sce.trustAsHtml(data.embed.html); 
     } 
    }, function (data) { 
     alert('Error: no data returned') 
    }); 


}); 

回答

2

你需要設置的指令範圍的變量,並設置模板標籤之間進行迭代:

 template : '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>', 
     scope : { 
      tagSrc : '=' 
     }, 

,並會成爲這樣的:

app.directive('tagIt', function(){ 
    return { 
     restrict: 'A', 
     template : '<li data-ng-repeat="tag in tagSrc">{{tag.name}}</li>', 
     scope : { 
      tagSrc : '=' 
     }, 

     link: function(scope,elem, attr) { 

      console.log(attr.tagSrc); 
     } 
    } 
}); 

'='屬性將告訴角度使用與HTML中的指令聲明中傳遞的數組進行綁定。

Here is a plunker with a working example.

而且here是一個很好的arcticle地名釋義指令的屬性和生命週期。

我希望它有幫助。

[編輯]

如果你只想遍歷數組,而無需創建列表中的項目的一些不同的行爲,你可以簡單地使用NG-重複指令:

<ul> 
    <li data-ng-repeat="tag in tags">{{tag.name}}</li> 
<ul> 
+0

這是模型答案!謝謝。就我而言,我不能使用ng-repeat,因爲我正在做的是真正包裝一個jQuery插件。我需要實際構建HTML片段並使用'elem.html()'將其添加到DOM,以便在應用'elem.tagIt()'時,jQuery函數'.tagIt'將執行其變換。但我無法弄清楚如何訪問tagSrc。我在控制檯中的對象中看到它,但無法訪問其訪問器。我會問這是一個單獨的問題。 – metalaureate

+0

按照這裏http://stackoverflow.com/questions/19645531/how-to-access-scope-collection-object-in-directive-to-manually-construct-html-sn – metalaureate

+0

謝謝!我現在看到這個問題,但它注意到你有一個解決方案=)很好! –

相關問題