簡體   English   中英

從Controller調用Directive方法:AngularJS

[英]Calling Directive method from Controller : AngularJS

我創建了如下指令

.directive("sampleInstructionOne",['$q' , '$rootScope',  'HigiKioskStorageService', 'HigiKioskUtilitiesService',function($q, $rootScope, HigiKioskStorageService,HigiKioskUtilitiesService) {
    //Weight instruction 1
    return {
        restrict : 'E',
        scope : false,
        templateUrl : 'components/weight/ecg-instruction-1.html',
        link : function(scope, element, attr){
            scope.weightInstruction = scope.weightInstruction || new Object();
            scope.weightInstruction.isHigi= HigiKioskUtilitiesService.isHigiGreen();

            scope.weightInstruction.bmcAnimationOne = function(){
                var q = $q.defer();
                $('.bmc_instruction_place').css('opacity', 1);
                $('#bmc_instruction_place_frames').delay(50)//we don't want to use a timeout, so we use a delay
                    .animate({'backgroundPosition':'left top'}, 1, function () { //a dummy function to "restart" the animation at first frame AND have a callback where we set the sprite
                        $('#bmc_instruction_place_frames').sprite({ //sets the sprite and animates it immediately
                            fps:(scope.weightInstruction.isHigi) ? 24 : 18,
                            no_of_frames:(scope.weightInstruction.isHigi) ? 24 : 18,
                            start_at_frame:0,
                            play_frames:(scope.weightInstruction.isHigi) ? 24 : 18
                        });
                    })
                    .delay(2000)//a delay to wait until the sprite animation is completed. this number needs to be equal to how long the sprite animates
                    .animate({'backgroundPosition':'right top'}, 1, function () { //a dummy function to house the callback, but also to make sure the animation is at the last frame
                        q.resolve();
                        $('#bmc_instruction_place_frames').destroy(); //you MUST destroy the sprite if you want it to play again
                    });

                return q;
            };
            scope[attr.promisename].resolve();

        }
    }
}])

我需要在控制器中調用指令方法'scope.weightInstruction.bmcAnimationOne',我嘗試像以下進行調用,並最終顯示為“無法讀取屬性bmcAnimationOne未定義”。

 $scope.instructionTwo = [
            $scope.weightInstruction.bmcAnimationOne
        ];

當您嘗試在父控制器中訪問$ scope.weightInstruction.bmcAnimationOne時,由於bmcAnimation是一個承諾,因此它可能尚未完成,因此從控制器的角度來看,它尚未定義。

您應該等待,直到加載完畢,然后分配結果:

$scope.instructionTwo = [];
$scope.weightInstruction.bmcAnimationOne()
    .then(function (result) {
        $scope.instructionTwo.push(result));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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