2016-01-14 56 views
0

目前我正試圖運行一個函數來處理指令加載後的大小調整。總是,該函數在內容加載到指令之前運行,因此它不能正確調整大小。指令加載後的運行函數

下面是代碼的片段,我使用:

$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> 

該指令包含從服務器的一些異步調用。

任何關於如何等待指令完成加載然後將函數應用於由指令創建的內容的想法都是受歡迎的。

我試過尋找$廣播和$發射,但由於某種原因,它似乎並沒有爲我工作。

在此先感謝。

編輯1:我更新了代碼,以更多地反映我在項目中的內容。

+0

如何將'ng-if'改爲'ng-show'? –

+0

@Egan不幸的是,如果切換變量設置爲false,則ng-show不會從指令中重置範圍。 – Scombine

回答

0

爲什麼沒有指令中的控制器,並從那裏製作按鈕?

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> 
+0

謝謝你的回覆。無論指令是否存在以及它處理與頁面不同的div,特殊調整大小函數都可以工作。當指令加載時,它調整特定的div和指令。在指令中包含resize函數將會阻止正常的div調整自身的大小。 – Scombine

0

我設法通過設置在$ 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 
    } 
} 
相關問題