从Controller调用Directive方法:AngularJS

时间:2019-01-27 17:13:33

标签: javascript angularjs angularjs-directive controller

我创建了如下指令

.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
        ];

1 个答案:

答案 0 :(得分:0)

当您尝试在父控制器中访问 $ scope.weightInstruction.bmcAnimationOne 时,由于 bmcAnimation 是一个承诺,因此它可能尚未完成,因此对于控制器的角度,尚未定义。

您应该等待其加载完毕,然后分配结果:

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