簡體   English   中英

如何在父級上使用ng-show進行指令以在show上觸發函數

[英]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類后,該指令才能執行某些操作(換句話說,只有“顯示”),我該怎么做?

謝謝!

AngularJS ng-show指令

如果表達式的計算結果為true,則ng-show指令將顯示指定的HTML元素,否則將隱藏HTML元素。


干得好。 我為您提供了AngularJS中的自定義指令的示例,如果狀態值等於true,則顯示一行語句。 希望這對您有所幫助。 干杯!

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM