本文介绍了Angularjs - 将参数传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道是否有办法将参数传递给指令?
Im wondering if there is a way to pass an argument to a directive?
我想要做的是从控制器附加一个指令,如下所示:
What I want to do is append a directive from the controller like this:
$scope.title = "title";
$scope.title2 = "title2";
angular.element(document.getElementById('wrapper')).append('<directive_name></directive_name>');
是否可以同时传递一个参数,以便我的指令模板的内容可以链接到一个或另一个范围?
Is it possible to pass an argument at the same time so the content of my directive template could be linked to one scope or another?
这里是指令:
app.directive("directive_name", function(){
return {
restrict:'E',
transclude:true,
template:'<div class="title"><h2>{{title}}</h3></div>',
replace:true
};
})
如果我想使用相同的指令但使用 $scope.title2 怎么办?
What if I want to use the same directive but with $scope.title2?
推荐答案
以下是我解决问题的方法:
Here is how I solved my problem:
指令
app.directive("directive_name", function(){
return {
restrict: 'E',
transclude: true,
template: function(elem, attr){
return '<div><h2>{{'+attr.scope+'}}</h2></div>';
},
replace: true
};
})
控制器
$scope.building = function(data){
var chart = angular.element(document.createElement('directive_name'));
chart.attr('scope', data);
$compile(chart)($scope);
angular.element(document.getElementById('wrapper')).append(chart);
}
我现在可以通过相同的指令使用不同的范围并动态附加它们.
I now can use different scopes through the same directive and append them dynamically.
这篇关于Angularjs - 将参数传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!