2015-05-07 70 views
2

我正在尝试编写一个非常简单的指令,它涉及到基于提供的属性之一设置属性。我面临的问题是attrs对象的值在link函数中没有得到一致的认可。角度指令中'attrs'属性无法正常工作

这里是总计的什么我正在努力实现:

angular.module('directives').directive('wikiNotes',function() { 
    return { 
     restrict: 'EA', 
     templateUrl: 'common/directives/wiki-notes.tpl.html', 
     link: function(scope, element, attrs) { 

      console.log(attrs.openEdit); //true 

      if(attrs.openEdit===true){ 
       console.log('open edit'); //not called 
      } 
     } 
    }; 
}); 

console.log(attrs.openEdit)被显示为真,但随后在ifconsole.log是没有得到调用。我是否错过了一些非常明显的东西,或者这是一个带角度指令的怪癖吗?

+0

我发现了这个问题。 'attrs.openEdit'被赋予'true'作为字符串,而不是布尔值。对于跳枪和张贴道歉。 – abyrne85

+1

这是一个很好的发现。您必须将其作为答案发布。 –

+0

所有属性都被串行化为一个字符串。当你想传递一个对现有对象实例的引用时,这可能非常烦人。 – HankScorpio

回答

1

您是否考虑在指令作用域中添加此属性? 我认为这是更多的Angular哲学,但这意味着你为你的指令创建一个新的范围。

angular.module('directives') 
.directive('wikiNotes',function() { 
    return { 
     restrict: 'EA', 
     scope: { 
      openEdit: '=' 
     }, 
     templateUrl: 'common/directives/wiki-notes.tpl.html', 
     link: function(scope) { 

      console.log(scope.openEdit); //true 

      if(scope.openEdit===true){ 
       console.log('open edit'); //should be a boolean 
      } 
     } 
    }; 
}); 

这是一个JS小提琴,演示它的工作原理。 https://jsfiddle.net/c8mn9wka/3/