我有一个带有ng-show的div。这个div是我创建的自定义指令的包装器。
HTML
<div ng-show="mycondition">
<div my-directive></div>
</div>
JS
function myDirective() {
function doSomthing() {...}
}
angular.module('myapp').directive('myDirective', myDirective);
我希望指令做一些事情,只有从包装div中删除ng-hide类(换句话说,只有“on show”) 我怎样才能做到这一点?
谢谢!
答案 0 :(得分:0)
如果表达式的计算结果为true,则ng-show
指令显示指定的HTML元素,否则隐藏HTML元素。
var app = angular.module("myApp", []);
app.controller("appCtrl", function($scope) {
$scope.status = true;
});
app.directive("myDirective", function() {
return {
restrict: "A",
template: "<h1>Made by a directive!</h1>"
};
});
&#13;
<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-controller="appCtrl">
<div ng-show="status">
<div my-directive></div>
</div>
</body>
</html>
&#13;
答案 1 :(得分:0)
有趣!以下是我想解决的问题:
我会像这样添加ng-show
:
ng-show="mycondition && doSomething()"
现在,只要你的条件符合即,只要doSomething
真实,它就会调用ng-show
函数。
很酷,让我们将此函数添加到myDirective
,我们将console.log
在函数内部,以了解它是否被调用。像这样:
app.directive("myDirective", function() {
return {
restrict: "A",
scope: {
doSomething: "="
},
template: "<h5>inside myDirective!</h5>",
controller: function($scope) {
$scope.doSomething = function() {
console.log("myDirective doing something");
return true; // Important, this function being a condition of ng-show needs to return true
}
}
};
});
现在,最后,让我们来调用我们的指令:
<div ng-show="mycondition && doSomething()">
<div my-directive do-something="doSomething"></div>
</div>
查找下面的工作代码段。此外,还有一个切换按钮可切换mycondition
,以证明在true
时调用它。
很少有事情需要注意,
true
,因为它是我们ng-show
的条件digest cycle
,函数被多次调用。但是我们可以通过在myDirective
范围内设置一个私有变量来摆脱这种行为,该变量在访问时设置为true
;阻止在true
时输入,并在工作完成时设置为false
。
var app = angular.module("myApp", []);
app.controller("appCtrl", function($scope) {
$scope.mycondition = true;
$scope.changeCondition = function() {
$scope.mycondition = !$scope.mycondition;
}
});
app.directive("myDirective", function() {
return {
restrict: "A",
scope: {
doSomething: "="
},
template: "<h5>inside myDirective!</h5>",
controller: function($scope) {
$scope.doSomething = function() {
console.log("myDirective doing something");
return true;
}
}
};
});
<!DOCTYPE html>
<html ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-controller="appCtrl">
<button ng-click="changeCondition()">toggle</button>
<div ng-show="mycondition && doSomething()">
<div my-directive do-something="doSomething"></div>
</div>
</body>
</html>