2013-10-28 41 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

谢谢!我现在看到这个问题,但它注意到你有一个解决方案=)很好! –

相关问题