【问题标题】:AngularJS: use ng-if in choosing a partial template in directiveAngularJS:使用 ng-if 在指令中选择部分模板
【发布时间】:2015-08-13 14:59:09
【问题描述】:

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

<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: '?=',方法是使其成为可选
  • @PankajParkar,这似乎不起作用,因为我现在遇到了一个新错误:错误:[$compile:iscp]

标签: javascript angularjs templates angularjs-directive compilation


【解决方案1】:

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

scope: {
   enablerowselection: '=?'
},

如果您在指令中需要该值,则应将其作为属性添加到指令元素中

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

基本上你应该在该属性中添加范围变量,当你使用=时,这将得到两种方式绑定

链接功能

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
}

【讨论】:

  • 感谢您的回复,但我不断收到相同的错误:错误:[$compile:nonassign]
  • @TonyGW 你能在你有my-directive的地方添加标记吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-10
  • 1970-01-01
相关资源
最近更新 更多