带有默认选项的Angular指令

Ken*_*eld 143 javascript options default-value angularjs angularjs-directive

我刚开始使用angularjs,我正在努力将一些旧的JQuery插件转换为Angular指令.我想为my(element)指令定义一组默认选项,可以通过在属性中指定选项值来覆盖它.

我已经浏览了其他人的方式,在angular-ui库中,ui.bootstrap.pagination似乎做了类似的事情.

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

.constant('paginationConfig', {
  itemsPerPage: 10,
  boundaryLinks: false,
  ...
})
Run Code Online (Sandbox Code Playgroud)

然后将getAttributeValue实用程序函数附加到指令控制器:

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

最后,这在链接函数中用于读入属性

.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);
        ...
    }
});
Run Code Online (Sandbox Code Playgroud)

对于想要替换一组默认值的标准内容,这似乎是一个相当复杂的设置.还有其他方法可以做到这一点吗?或者getAttributeValue以这种方式总是定义一个实用程序函数(如和解析选项)是否正常?我很想知道人们对这项共同任务采取了哪些不同的策略.

另外,作为奖励,我不清楚为什么interpolate需要这个参数.

小智 256

=?在指令的作用域块中使用该属性的标志.

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';
      }
    }
  });
Run Code Online (Sandbox Code Playgroud)

  • 如果你的属性可以接受`true`或`false`作为值,你会(我认为)想要使用例如`$ scope.hasName = angular.isDefined($ scope.hasName)?$ scope.hasName:false;`而不是. (34认同)
  • 注意:它只适用于双向绑定,例如`=?`,但不适用于单向绑定,`@?`. (21认同)
  • 也可以只在模板中完成:template:'hello {{name || \'默认名称\'}}' (20认同)
  • `=?`自1.1.x起可用 (4认同)
  • 是应该在控制器中还是在`link`功能中设置默认值?根据我的理解,在`link`期间分配应避免使用`$ scope.$ apply()`循环,不应该吗? (4认同)

OZ_*_*OZ_ 108

您可以使用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; }
    },
        ...
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 请记住,属性需要从模板传递的值.如果你传递一个数组,它应该是`attributes.foo ='["one","two","three"]'`而不是`attributes.foo = ["one","two","three "]` (4认同)
  • 在`compile`中的@KenChatfield你无法读取属性,应该插值以获取值(包含表达式).但是如果你只想检查属性是否为空 - 它将在没有任何权衡的情况下工作(在插值属性将包含带表达式的字符串之前). (3认同)