javascript - AngularJS:使用 ng-if 在指令中选择部分模板

标签 javascript angularjs templates angularjs-directive compilation

我的指令需要在其模板内的两个部分模板之间进行选择:

<div ng-if="enablerowselection" ui-grid="gridOptions" ui-grid-pagination ui-grid-selection class="grid"></div>

        <div ng-if="!enablerowselection" ui-grid="gridOptions" ui-grid-pagination class="grid"></div>

在我的指令的链接器函数中,我从属性中获取enablerowselection的值:

function linker(scope, element, attrs) {
   scope.enablerowselection = attrs.enablerowselection; //enablerowselection is an attribute for my directive
}

但是,这会导致以下错误:

Error: [$compile:nonassign]

我想我需要编译指令内的部分模板,所以我在链接器函数中添加了以下内容,但它仍然不起作用:

$compile(element.contents())(scope);

编辑:以下是我的指令代码:

angular.module('myApp')
    .directive('myDirective', myDirective);

myDirective.$inject = ['$compile'];

function myDirective($compile) {
   return {
     restrict: 'EA',
     scope: {
        enablerowselection: '='
      },
     templateUrl: '/path/to/directive_tmpl.html',
     link: linkerFn

    };

 function linkerFn(scope, element, attrs) {
     $scope.enablerowselection = attrs.enablerowselection;
     $compile(element.contents())(scope); //does not help
  } //linkerFn
}

最佳答案

正如我所见,enablerowselection 在隔离范围内,您应该在指令中使用该属性作为可选属性,这样,如果未提供该属性,则指令将不会引发错误。您可以通过对该变量使用 =? 来创建隔离范围属性,例如

scope: {
   enablerowselection: '=?'
},

如果您在指令中需要该值,那么您应该将其添加为指令元素内的属性

<my-directive enablerowselection="enablerowselection"></my-directive>

基本上,您应该在该属性内添加作用域变量,当您使用 =

时,它将获得两种方式绑定(bind)

链接功能

function linkerFn(scope, element, attrs) {
     //scope.enablerowselection = attrs.enablerowselection; //reomve this
     //you already have value in `$scope.enablerowselection`,
     //you don't need to get it from attribute,
     //'=' in isolated scope means value of parent scope variable specified in attribute,
     //gets available inside the isolated scope(basically its two way binded.)
     $compile(element.contents())(scope); //does not help
}

关于javascript - AngularJS:使用 ng-if 在指令中选择部分模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31991847/

相关文章:

c++ - 确定 (c++) 迭代器是否反向

Javascript RegExp 用于将文本拆分为带引号的句子并保留分隔符

javascript - 将 CSS 转换为不同的格式 (JavaScript/jQuery)

javascript - 使用 JavaScript 和 REST 从 SharePoint 列表中删除项目

javascript 循环思想 bootstrap

javascript - 将 $scope 对象传递给路由,如果刷新则保留

javascript - 在 AngularJS 之后加载 jQuery

css - Angular - 用户界面网格 - 字体

django - 您将如何在 Django 应用程序和 Wordpress 博客之间共享主题?

c++ - 有没有为特定模板值添加成员变量的方法?