[英]how to make directive with ng-show on the parent to trigger a function on show
我有一個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類后,該指令才能執行某些操作(換句話說,只有“顯示”),我該怎么做?
謝謝!
如果表達式的計算結果為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>" }; });
<!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>
有趣! 這是我要解決的方法:
我會這樣添加ng-show
:
ng-show="mycondition && doSomething()"
現在,只要您的條件滿足, 即 ng-show
是真實的,它將調用doSomething
函數。
很酷,讓我們將該函數添加到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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.