2015-11-12 60 views
0

我正在使用UI Bootstrap的datepicker函数,我想获取传入属性的值之一。Angular指令字段不需要括号

// 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); 
      }; 
     }; 

回答

3

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

在你的代码

所以,看到实际值使用:

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

这也是为什么该指令不需要双大括号。实际上,双括号会导致问题,因为它会将您的对象转换为字符串,并因此丢失对象的方法Date

有关$eval方法看AngularJS Scope API

+0

啊,谢谢。/10char – diplosaurus

0

对于初学者,您将覆盖整个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); 
      }; 
     }; 

.... 
+0

更多信息,这是不是覆盖现有'link'方法? – diplosaurus

+0

否,因为链接是一个可以从编译中返回的函数,并且旧链接(及其编译结果)将被保存为与之前类似的内容。 – Shaun

相关问题