2017-02-08 3 views
2

ng-showがtrueに設定され、以前の非表示の要素が表示されているときに、コントローラ上で関数を呼び出すことはできますか?内部の要素が隠されているから可視になるときに、関数を実行するためのディレクティブが必要です。非表示の要素が表示されたときの呼び出し関数

<div ng-show="showOrNot" > 
 
    This is secret text. 
 
    <my-directive> I need to call a function </my-directive> 
 
    </div>

+0

関数を呼び出すためにNG-INITを使用することができます。 – Jenny

+0

いいえ、それはトリガーされません。 – Lautaro

答えて

2

あなたは、関数を呼び出すと、ここ NG-IFを使用するNG-INITを使用することができます例です。

var app = angular.module('app',[]); 
 
app.controller('Demo',['$scope', Demo]); 
 
function Demo($scope){ 
 
    $scope.showOrNot = false; 
 
    $scope.Show = function(){ 
 
    $scope.showOrNot = true; 
 
    alert("shown"); 
 
    } 
 
    $scope.hello = function(){ 
 
    alert("function call!"); 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div ng-app="app" ng-controller="Demo"> 
 
<div ng-if="showOrNot"> 
 
    <div ng-init="hello()">This is secret text.</div> 
 
</div> 
 
    <button ng-click="Show()">click</button> 
 
    </div>

2

あなたは、単にあなたのディレクティブのスコープにshowOrNotスコープを渡すことができます。その後、$watchそれを変更し、値が変更された後に必要なロジックを追加します。

単に:次に

<my-directive value-to-watch="showOrNot">I need to call a function</my-directive> 

ディレクティブ:

angular.module('app').directive('myDirective', function() { 
    return { 
    restrict:'E', 
    scope: { 
     valueToWatch:'=' 
    }, 
    controller: function($scope) { 
     $scope.$watch('valueToWatch', function (newValue, oldValue) { 
      //Case when new value is true and old value is false 
      if(newValue && !oldValue) { 
      //Call the function you want 
      } 
     }); 
    } 
    } 
}) 
-1

あなたはそれが真のときに関数を呼び出すためにinorderをコントローラ内で$時計を使用することができます。

<my-directive content="showOrNot"> I need to call a function </my-directive> 

.directive('myDirective', function() { 
    return { 
    restrict: 'E', 
    scope: { 
     content: '=', 
    } 
    link: function (scope, element) { 
     scope.$watch('content', function (newvalue, oldvalue) { 
     if(newvalue == true) 
     { 
      //your function here 
     } 
    }); 
    } 
    } 
} 

このような名前を書くことができます。

関連する問題