javascript - 检查链接函数中隔离范围变量的值 - Angular Directive(指令)

标签 javascript html angularjs angularjs-directive angularjs-scope

我有以下 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 正文中,我这样做:

<!-- Modal body-->

<div class="modal-body">

    <table-directive list=list headers=headers></table-directive>

</div>

我想检查我传入的list参数。如果它等于某个值,我想在正文中附加一些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 属性,并将参数作为表达式而不是字符串执行,我认为您尝试将 'pctrl' 作为字符串而不是范围变量值获取,以便更改为 list="'pct​​rl'" 以作为字符串传递

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

使用@获取字符串形式的attr

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

这是一个很好的Explanation .

这里是 Angular 官方 DOC

更新

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

所以在指令中使用它作为

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

关于javascript - 检查链接函数中隔离范围变量的值 - Angular Directive(指令),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31473445/

相关文章:

javascript - Bootstrap Modal 在用作 UL Listitem 时卡住页面

javascript - 在 react 中更新一个状态时更新多个集合

html - 字体系列声明不起作用

javascript - ngRepeat 中的变量在 ngClick 中不起作用

html - 居中文件输入表单 - html/bootstrap/angular

javascript - 收到表情符号 react 后的 Discord.js 消息

javascript - 这些 jQuery 语句的含义是什么或者它们有什么作用?

html - 带有箭头 css 的聊天消息 block

javascript - 不能使用 2 个 js 函数,它们之间有 sleep

javascript - 使用 Express API 和 ReactJS SPA 进行路由