检查angular中链接函数指令中孤立作用域变量的值

check value of isolated scope variable in link function - directives in angular

本文关键字:作用域 变量 指令 angular 链接 函数 检查      更新时间:2023-09-26

我有以下html:

<div class="jumbotron" ng-controller="protocolCtrl as pctrl">
    <!--IN THIS MODAL YOU CAN ADD/CHANGE/DELETE DATA-->
    <modal-directive list="pctrl" headers="['ID', 'Protocol']"></modal-directive>
</div>

在我的modal-directive.html中,在body中,我这样做:

<!-- Modal body-->
<div class="modal-body">
    <table-directive list=list headers=headers></table-directive>
</div>

我想检查我传入的list参数。如果它等于某个值,我想在body

后面添加一些html

我的指令是这样的

.directive('modalDirective', function(){
    return {
        restrict: 'E',
        templateUrl: '/directives/modal-directive.html',
        scope: {
            list: '=',
            headers: '='
        },
        link: function(scope, element, attrs){
            if(scope.list == 'pctrl'){
                element.find('.modal-body').append('This is just a test.')
            }
        }
    };
});

但是这并没有附加任何东西。如果我去掉if检查,它就会很好地追加。

我对angular相当陌生,所以如果有人能告诉我如何才能做到这一点,我将不胜感激。

编辑

这就是我如何循环通过我的table-directive.html

中的数据
 <tr ng-repeat="l in list.list">
     <!--Access the actual values inside each of the objects in the array-->
     <td ng-repeat="data in l"> {{ data }} </td>
     <td>
         <button type="button" class="btn btn-primary btn-sm"
                 data-toggle="modal">Edit</button>
     </td>
     <td>
        <button type="button" class="btn btn-danger btn-sm" ng-click="list.removeData(l)"
                    data-dismiss="modal">Remove</button>
     </td>
 </tr>

如果你把

<modal-directive list="pctrl" headers="['ID', 'Protocol']"></modal-directive>

....
  scope: {
        list: '=',
        headers: '='
    },
.....

list: '='检查元素的list attr并将参数作为表达式执行,而不是作为字符串我认为您试图将'pctrl'作为字符串而不是作为范围变量值,以便更改为list="'pctrl'"作为字符串传递

<modal-directive list="'pctrl'" headers="['ID', 'Protocol']"></modal-directive>

使用@

获取attr作为字符串
....
  scope: {
        list: '@',
        headers: '='
    },
.....

这是一个很好的解释。

这里是angular的官方DOC

如果您只需要检查attr的字符串值,那么您只需使用attrs.list

所以在指令中使用

if(attrs.list === 'pctrl'){
    element.find('.modal-body').append('This is just a test.')
}