加载指令后运行函数



目前我正在尝试运行一个函数,该函数在加载指令后处理大小调整。始终,该函数在指令中加载内容之前运行,因此它不会正确调整大小。

这是我正在使用的代码片段:

    $scope.myToggleFunctionForDirective() = function(){
       $scope.changeableVariable = !$scope.changeableVariable
       myResizeFunction();
    }
    window.myResizeFunction = function (){           
       //do something
    }

html看起来像这样

    <button ng-click="myToggleFunctionForDirective()"></button>
    <my-directive ng-if="changeableVariable"></div>

该指令包含来自服务器的一些异步调用。

欢迎任何关于如何等待指令完成加载,然后将函数应用于指令创建的内容的想法。

我试着查看$broadcast和$emit,但由于某种原因,它似乎对我不起作用。

提前谢谢。

编辑1:我更新了代码以更多地反映我在项目中的内容。

为什么不在指令中有一个控制器,并从那里制作按钮?

angular.module('myApp')
    .directive('myToggleButton', myToggleButton);
/* @ngInject */
function myToggleButton() {
    var directive = {
        restrict: 'E',
        bindToController: true,
        controller: myToggleController,
        // your other directive pieces, scope, restrict, etc
    };
    return directive;
}
function myToggleController() {
    var vm = this;
    vm.reSize = reSize;
    function reSize() {           
        //do something
    }
}

在您的按钮中:

<my-toggle-button data-ng-click="vm.reSize()"></my-toggle-button>

我设法通过在$rootScope上设置变量并在我的页面中添加一个观察者来解决这种情况。在指令中,我将该特定变量设置为 true,在页面中,一旦满足某些条件,该变量将设置为 false。希望这将帮助其他人解决问题。

//app.js file:
$rootScope.myVariable = false;
//directive file
$rootScope.myVariable = true
//main page file:
$rootScope.$watch ('myVariable', function (){
   if($rootScope.myVariable){
       myResizeFunction();
   }
});
$scope.myToggleFunctionForDirective() = function(){
   $scope.changeableVariable = !$scope.changeableVariable
   if($scope.changeableVariable) {
      $rootScope.myVariable = false
   }
}

最新更新