AngularJS:将 $scope 变量作为指令属性传递 [英] AngularJS : Pass $scope variable as directive attribute

查看:27
本文介绍了AngularJS:将 $scope 变量作为指令属性传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 $scope 变量值作为属性传递给自定义指令,但它不起作用.

I'm trying to pass the $scope variable values to a custom directive as attribute, but it's not working.

这是HTML代码:

<ul ng-repeat="q in questions">
        <li>
            {{q.question}} 
            <check-list name="{{q.id}}"></check-list>
        </li>
</ul>

指令是<check-list name={{q.id}}></check-list>,这里是指令代码:

The directive is <check-list name={{q.id}}></check-list>, and here is the directive code :

    app.directive('checkList',function(){
    return {
        restrict:'E',
        template: function(elem,attrs){
            console.log(attrs.name);
            return '</br> <input type="radio" /> Yes </br> <input type="radio" /> No'
        },
        link:function(scope,elem,attrs){

        }
    };
})

我正在记录属性 attrs.name 但我得到的值是 "{{q.id}}" 而不是 "{{q.id}}" 的实际值代码>q.id

I'm logging the attribute attrs.name but the value I'm getting is "{{q.id}}" instead of the actual value of q.id

推荐答案

我想你想做的是将作用域对象从控制器注入到你的指令中.所以你可以将你的指令定义为

I suppose what you want to do is injecting scope object from controller to your directive. So you can define your directive as

app.directive('checkList',function(){
    return {
        restrict:'E',
        scope: {
          name: "="
        }
        template: '{{name}}</br> <input type="radio" /> Yes </br> <input type="radio" /> No',
        link:function(scope,elem,attrs){

        }
    };
}

在您看来,您可以将指令引用为

And in your view, you can reference your directive as

<check-list name="q.id"></check-list>

这篇关于AngularJS:将 $scope 变量作为指令属性传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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