显示隐藏元素时调用函数

时间:2017-02-08 10:55:49

标签: angularjs

当ng-show设置为true并且前一个隐藏元素可见时,是否可以在控制器上调用函数?我需要一个指令来运行一个函数,当它在里面的元素从隐藏变为可见时。



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

3 个答案:

答案 0 :(得分: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 :(得分:2)

您可以使用 ng-init 来调用功能并使用 ng-if 这里是示例:

&#13;
&#13;
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!");
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

你可以在控制器中使用$ watch,以便在真实时调用函数。

  <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
       }
     });
     }
  }
}
你可以写这样的东西。

相关问题