为什么AngularJS在定义时会在指令中显示范围变量未定义?

时间:2016-01-11 03:31:59

标签: javascript angularjs angularjs-directive angularjs-scope

我有一个由:

调用的angularJS指令
<rpt-closing closing-begin-ts="null" closing-begin-ts="'2014-11-25 23:59:59'"></rpt-closing>

指令代码如下:

  .directive('rptClosing',function(){
      return {
        restrict:'E',
        scope: {
          closingBeginTs: '=',
          closingEndTs: '='
        },
        link: function(scope, element, attrs) {
          console.log('*******************************************');
          console.log('scope = ', scope);
          console.log('scope.closingBeginTs = ', scope.closingBeginTs);
          console.log('scope.closingEndTs = ', scope.closingEndTs);
          console.log('*******************************************');
        },
        template: '<div>BLAH BLAH BLAH</div>'
      };
    }
  )

此代码在the jsFiddle中完全正常。我可以在控制台输出中看到scope.closingBeginTsscope.closingEndTs的值。

enter image description here

3 个答案:

答案 0 :(得分:6)

它记录为未定义,因为它未定义。在您提供的代码段中,这两个属性均为closing-begin-ts

<rpt-closing closing-begin-ts="null" 
             closing-begin-ts="'2014-11-25 23:59:59'">  
</rpt-closing>

当然应该是:

<rpt-closing closing-begin-ts="null" 
             closing-end-ts="'2014-11-25 23:59:59'">  
</rpt-closing>

答案 1 :(得分:2)

根据你的例子,我试过

<rpt-closing closing-begin-ts="null" 
         closing-begin-ts="'2014-11-25 23:59:59'"> </rpt-closing>

结果是:      closingBeginTs &#39; null&#39; closingEndTs &#39; undefined&#39; as你没有在HTML中使用它

如果你这样定义:

<rpt-closing closing-begin-ts="null" 
         closing-end-ts="'2014-11-25 23:59:59'"> </rpt-closing>

结果是:      closingBeginTs &#39; null&#39; closingEndTs &#39;&nbsp; 23:59:59&#39;&#39; 因为你没有在HTML中使用它

您也可以尝试在范围内传递属性名称。

答案 2 :(得分:0)

您需要传递属性名称

.directive('rptClosing',function(){
      return {
        restrict:'E',
        scope: {
          closingBeginTs: '=closingBeginTs',
          closingEndTs: '=closingEndTs'
        },
        link: function(scope, element, attrs) {
          console.log('*******************************************');
          console.log('scope = ', scope);
          console.log('scope.closingBeginTs = ', scope.closingBeginTs);
          console.log('scope.closingEndTs = ', scope.closingEndTs);
          console.log('*******************************************');
        },
        template: '<div>BLAH BLAH BLAH</div>'
      };
    }
  )