【发布时间】:2015-10-07 12:41:35
【问题描述】:
在我的控制器的原始版本中,我在 dom 中添加了一个标头徽标,然后能够在调用函数时将其删除并替换为其他内容,就像这样
$scope.addHeader('.blahClassName');
$scope.removeHeaderFunction = function(){
$('.blahClassName).html('');
//do other stuff
}
这很好用。但是,我读到最好不要在控制器中进行 DOM 操作,因此我创建了这样的指令
<div class='MyCtrl as vm'>
<div header-dir myscope="vm" removeheaderflag="{{vm.headerflag}}"></div>
然后,在我的指令的链接函数中,我添加标题标志并监听标志的变化以将其删除,就像这样
link: function(scope, elem, attrs){
scope.myscope.addHeader('.blahClassName'); //calling the function addHeader on the controller available through myscope
attrs.$observe('removeheaderflag', function(){
angular.element(elem[0].querySelector('.blahClassName')).html('');
});
}
然后在控制器中,我在页面加载时设置$scope.headerflag = null;,并在removeHeaerFunction 中将其设置为true,目的是仅当标志设置为true 时才会删除标题
$scope.removeHeaderFunction = function(){
$scope.headerflag = true;
}
但是,我的代码的实际行为是立即添加和删除徽标,无论 $scope.headerflag 设置为什么。也就是说$attrs.observe('removeheaderflag', ...里面的代码是立即运行的。
问题:如何在该观察者中延迟代码的运行或以其他方式从指令中获得我想要的行为,即基本上能够在点击事件中删除某些内容
【问题讨论】:
-
您使用的是标准点击事件还是 ng-click?听起来您没有从角度生命周期内设置控制器值,因此更改不会立即反映。
标签: javascript html angularjs angularjs-directive dom-manipulation