如何检查是否已向指令提供表达式属性?

时间:2013-11-13 19:46:53

标签: angularjs angularjs-directive

我创建了一个接受回调作为属性的指令,例如:

<my-directive callback-expression="someFunction()"> </my-directive>

该指令是可重用的,因此我给它一个隔离范围。我想根据是否设置callback-expression属性在指令中显示一个按钮。

App.directive('myDirective', function(){
  restrict: 'E',
  scope:    {
              callbackExpression: '&'
            },
  template: '<button ng-show="!!callbackExpression">Fire callback</button>'
});

问题是,即使表达式为空,它也是一个函数:

带有空白属性的

console.log($scope.callbackExpression)会导致:

function (locals) {
  return parentGet(parentScope, locals);
}

我目前的解决方案是将此行放在链接功能的顶部:

if (attributes.callbackExpression) scope.callbackButton = true

然后ng-show上的callbackButton

是否有任何替代方案不需要额外的线路&amp;范围属性?

2 个答案:

答案 0 :(得分:3)

如果您想避免在堆栈上放置任何内容,那么您可以使用链接功能,您可以通过attrs访问属性。以下是两种方法:

链接功能选项1:

您可以在指令中使用此链接功能,而不是使用模板,该指令有条件地添加模板:

link: function (scope, element, attrs) {     
     if (attrs.callbackExpression) {
         var html = '<button>Fire callback</button>';
         element.replaceWith(html);
     }
}

选项1演示:http://jsfiddle.net/ZC4MZ/2/

链接功能选项2(适用于大型模板):

对于大型模板,您可以使用$templateCache。首先添加模板:

myApp.run(function($templateCache) {
  $templateCache.put('myDirective.html', '<button>Fire callback</button>');
});

然后有条件地使用它,就像选项1一样,但使用$templateCache.get()

link: function (scope, element, attrs) {     
    if (attrs.callbackExpression) {
        var html = $templateCache.get('myDirective.html');
        element.replaceWith(html);
    }
}

确保将$templateCache注入您的指令:

myApp.directive('myDirective', function ($templateCache) {

以下是使用$templateCachehttp://jsfiddle.net/ZC4MZ/3/

的演示

仅使用模板的选项:

要使用模板,您需要在示波器上使用变量。为此,您可以保留所有内容,只需添加:

link: function(scope, element, attrs) {
      scope.callbackExpression = attrs.callbackExpression;}
}

模板/范围变量演示:http://jsfiddle.net/ZC4MZ/5/

答案 1 :(得分:1)

您可以使用directives中可以注入的$ attrs对象来获取此信息。

标记:

  <body ng-app="myApp" ng-controller="MyController">
    <my-directive text="No Expression"></my-Directive>
    <my-directive text="Expression" callback-expression="myCallback()"></my-Directive>
  </body>

JS:

app.directive('myDirective', function(){

  return {
    restrict: "E",
    scope: {
      text: '@',
      callbackExpression:'&'
    },
    templateUrl: "partial.html",
    link: function($scope, $elem, $attrs) {
      $scope.expressionCalled = false;
      if ($attrs.callbackExpression) {
        $scope.expressionCalled = true;
      }
    }
  }

});

我为这个例子创建了一个工作插件: http://plnkr.co/edit/K6HiT2?p=preview