带有默认选项的AngularJS指令

152

我刚开始接触AngularJS,并且正在将几个旧的jQuery插件转换为Angular指令。我想为我的(元素)指令定义一组默认选项,可以通过在属性中指定选项值来覆盖。

我查看了一些其他人是如何做到这一点的,而在angular-ui库中,ui.bootstrap.pagination似乎做了类似的事情。

首先,所有默认选项都定义在一个常量对象中:

.constant('paginationConfig', {
  itemsPerPage: 10,
  boundaryLinks: false,
  ...
})

然后,一个 getAttributeValue 的实用函数被附加到指令控制器上:

this.getAttributeValue = function(attribute, defaultValue, interpolate) {
    return (angular.isDefined(attribute) ?
            (interpolate ? $interpolate(attribute)($scope.$parent) :
                           $scope.$parent.$eval(attribute)) : defaultValue);
};

最后,在链接函数中使用它作为读取属性的方法。

.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
    ...
    controller: 'PaginationController',
    link: function(scope, element, attrs, paginationCtrl) {
        var boundaryLinks = paginationCtrl.getAttributeValue(attrs.boundaryLinks,  config.boundaryLinks);
        var firstText = paginationCtrl.getAttributeValue(attrs.firstText, config.firstText, true);
        ...
    }
});

对于想要替换一组默认值这样标准的操作,这似乎是一个相当复杂的设置。是否有其他常见的方法来做到这一点?或者通常是否需要定义像getAttributeValue这样的实用函数,并以这种方式解析选项?我很感兴趣了解人们在这个常见任务上有哪些不同的策略。

此外,额外奖励,我不清楚为什么需要interpolate参数。

3个回答

271

在指令的作用域块中,使用=?标记来设置属性。

angular.module('myApp',[])
  .directive('myDirective', function(){
    return {
      template: 'hello {{name}}',
      scope: {
        // use the =? to denote the property as optional
        name: '=?'
      },
      controller: function($scope){
        // check if it was defined.  If not - set a default
        $scope.name = angular.isDefined($scope.name) ? $scope.name : 'default name';
      }
    }
  });

5
=? 自1.1.x版本起可用。 - Michael Radionov
35
如果你的属性接受truefalse作为值,那么你(我认为)希望使用例如$scope.hasName = angular.isDefined($scope.hasName) ? $scope.hasName : false; - Paul D. Waite
23
注意:它只适用于双向绑定,例如 =?,但不适用于单向绑定,@? - Justus Romijn
20
也可以仅使用模板完成: 模板:'你好{{name || '默认名称'}}' - Vildan
5
默认值应该在控制器或link函数中设置?根据我的理解,在link期间进行赋值可以避免$scope.$apply()周期,是吗? - Augustin Riedinger
显示剩余6条评论

111
你可以使用compile函数- 如果未设置属性,则读取属性并使用默认值填充。
.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
    ...
    controller: 'PaginationController',
    compile: function(element, attrs){
       if (!attrs.attrOne) { attrs.attrOne = 'default value'; }
       if (!attrs.attrTwo) { attrs.attrTwo = 42; }
    },
        ...
  }
});

1
谢谢!那么,你有没有想过为什么 ui.bootstrap.pagination 以一种更复杂的方式处理事情?我认为如果使用编译函数,稍后进行的任何属性更改都不会反映出来,但是这似乎并不正确,因为此阶段仅设置默认值。猜想在这里必须做出某些权衡。 - Ken Chatfield
3
compile中,您无法读取属性,这些属性应该被插值以获取其中的值(该值包含表达式)。但是,如果您只想检查属性是否为空,则可以在不进行任何权衡的情况下使用它(在插值之前,属性将包含带有表达式的字符串)。 - OZ_
1
太棒了!非常感谢您清晰的解释。对于未来的读者,虽然与原始问题有些牵强,但是关于ui.bootstrap.pagination示例中'interpolate'参数的解释,我发现这个示例非常有用:http://jsfiddle.net/EGfgH/。 - Ken Chatfield
非常感谢您提供的解决方案。请注意,如果您需要“link”选项,则仍然可以在“compile”选项中返回一个函数。文档在此处 - mneute
4
请记住,属性需要按照从模板传递的方式进行赋值。如果您传递一个数组,则应该将其设置为 attributes.foo = '["one", "two", "three"]' 而不是 attributes.foo = ["one", "two", "three"] - Dominik Ehrenberg

2
我正在使用AngularJS v1.5.10,并发现 preLink 编译函数 可以很好地用于设置默认属性值。
仅作提醒:
- attrs 保存的是始终为 undefined 或字符串的原始 DOM 属性值。 - scope 包含(除其他外)根据提供的隔离作用域规范(= / < / @ / 等等)解析的 DOM 属性值。
简略片段:
.directive('myCustomToggle', function () {
  return {
    restrict: 'E',
    replace: true,
    require: 'ngModel',
    transclude: true,
    scope: {
      ngModel: '=',
      ngModelOptions: '<?',
      ngTrueValue: '<?',
      ngFalseValue: '<?',
    },
    link: {
      pre: function preLink(scope, element, attrs, ctrl) {
        // defaults for optional attributes
        scope.ngTrueValue = attrs.ngTrueValue !== undefined
          ? scope.ngTrueValue
          : true;
        scope.ngFalseValue = attrs.ngFalseValue !== undefined
          ? scope.ngFalseValue
          : false;
        scope.ngModelOptions = attrs.ngModelOptions !== undefined
          ? scope.ngModelOptions
          : {};
      },
      post: function postLink(scope, element, attrs, ctrl) {
        ...
        function updateModel(disable) {
          // flip model value
          var newValue = disable
            ? scope.ngFalseValue
            : scope.ngTrueValue;
          // assign it to the view
          ctrl.$setViewValue(newValue);
          ctrl.$render();
        }
        ...
    },
    template: ...
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接