2013-04-09 122 views
0

因此,在此示例中,ng-hide不会隐藏该元素。为什么以及如何解决这个问题?指令中的重新连接指令

<div ng-app='myApp'> 
    <input type='text' foo/> 
</div> 

angular.module('myApp',[]) 
    .directive('foo',function(){ 
    return{ 
     link:function(scope,element,attrs){ 
      element.after('<div style="width:200px; height:200px;' 
        +' background-color:red" ng-hide="true"></div>') 
     } 
    } 
}); 

http://jsfiddle.net/BL8h5/

+2

使用'$ compile'服务,以便指令和绑定被逮住。 – 2013-04-09 21:37:45

回答

2

看到这个更新例如:

http://jsfiddle.net/JxMTW/1/

angular.module('myApp',[]) 
.directive('foo',function($compile){ 
    return{ 
     link:function(scope,element,attrs){ 
      element.after($compile('<div style="width:200px; height:200px; background-color:red" ng-hide="true"></div>')(scope)) 
     } 
    } 
}); 

的原因是,这不是 '角' 的方式做的事情 - 你应该避免“搞乱了DOM',而是使用一个模板并让它处理它。

在您的特定情况下,您需要做的是通过$compile运行新元素,该元素解析内容并拾取任何角度逻辑。

欲了解更多信息,请参见该问题并回答: AngularJS and generated elements