Angularjs - 将参数传递给指令 [英] Angularjs - Pass argument to directive

查看:242
本文介绍了Angularjs - 将参数传递给指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种方法可以将参数传递给指令?



我想要做的是从控制器追加一个指令,如下所示:

  $ scope.title =title; 
$ scope.title2 =title2;

angular.element(document.getElementById('wrapper'))。append('< directive_name>< / directive_name>')

可以同时传递参数,所以我的指令模板的内容可以链接

  

app.directive(directive_name,function(){
return {
restrict:'E',
transclude:true,
template:'< div class = >< h2> {{title}}< / h3>< / div>',
replace:true
};
})
$ b h2_lin>解决方案

这是我如何解决我的问题:



指令
$ b

  app.directive(directive_name,function(){
return {
restrict:'E',
transclude:true,
template:function(elem,attr){
return'< div>< h2> {{'+ attr.scope +'}}< / h2>< / div ;';
},
replace:true
};
})

控制器 b

  $ 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);
}



现在可以通过相同的指令使用不同的范围,并动态添加它们。 / p>

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?

here is the directive:

app.directive("directive_name", function(){
    return {
        restrict:'E',
        transclude:true,
        template:'<div class="title"><h2>{{title}}</h3></div>',
        replace:true
    };
})

What if I want to use the same directive but with $scope.title2?

解决方案

Here is how I solved my problem:

Directive

app.directive("directive_name", function(){
    return {
        restrict: 'E',
        transclude: true,
        template: function(elem, attr){
           return '<div><h2>{{'+attr.scope+'}}</h2></div>';
        },
        replace: true
    };
})

Controller

$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 - 将参数传递给指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆