【问题标题】:Angular directive fields not require bracketsAngular 指令字段不需要括号
【发布时间】:2015-11-12 01:40:14
【问题描述】:

我正在使用 UI Bootstrap 的 datepicker 函数,我想获取传递给属性的值之一。

// JS
$scope.myMaxDate = new Date();

<!-- HTML -->
<input datepicker-popup="MM/dd/yyyy" max-date="myMaxDate" />

我不明白为什么在这种情况下max-date attr 接受一个字符串而不是像{{myMaxDate}} 这样的表达式。它是如何获取实际值的?

更重要的是,我正在使用装饰器来更改此指令中的一些数据,并希望访问此属性,但我得到的只是字符串 myMaxDate

    $provide.decorator("datepickerPopupDirective", ["$delegate", function($delegate) {
        // get references to the directive and old link function
        var directive = $delegate[0];
        var link = directive.link;

        // create a new link function using compile
        directive.compile = function() {
            // the new link function we want to return
            return function(scope, element, attrs, ngModelCtrl) {
                console.log(attrs.maxDate); // 'myMaxDate'

                // invoke the old link function
                link.apply(this, arguments);
            };
        };

【问题讨论】:

    标签: javascript angularjs angular-ui-bootstrap


    【解决方案1】:

    要回答您关于datepicker-popup 指令如何找到max-date 属性的实际值的问题,它很可能使用scope$eval 方法。

    所以在你的代码中,查看实际使用的值:

     console.log(scope.$eval(attrs.maxDate));
    

    这也是指令不需要双花括号的原因。事实上,双花括号会导致问题,因为它会将您的myMaxDate 对象转换为字符串,从而丢失Date 对象的方法。

    有关$eval 方法的更多信息,请查看AngularJS Scope API

    【讨论】:

      【解决方案2】:

      对于初学者,您将完全覆盖 compile。这会产生潜在的问题。

       $provide.decorator("datepickerPopupDirective", ["$delegate", function($delegate) {
              // get references to the directive and old link function
              var directive = $delegate[0];
              var compile = directive.compile;
      
              directive.compile = function() {
      
                  var link = compile.apply(this, arguments); 
      
                  // the new link function we want to return
                  return function(scope, element, attrs, ngModelCtrl) {
                      console.log(attrs.maxDate); // 'myMaxDate'
      
                      // invoke the old link function
                      link.apply(this, arguments);
                  };
              };
      
      ....
      

      【讨论】:

      • 这不会覆盖现有的link 方法吗?
      • 否,因为链接是一个可以从编译中返回的函数,并且旧链接(及其编译结果)的保存方式与您之前的类似。
      猜你喜欢
      • 2019-02-20
      • 2014-08-09
      • 1970-01-01
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2018-08-29
      • 2014-02-10
      相关资源
      最近更新 更多