通过Javascript更改数据目标

问题描述 投票:0回答:1

我正在开发一个AngularJS应用程序,我有一个类似的任务: 1)单击按钮。 2)如果variableA === true,则输出一个模态。 3)如果variableA === false,则转到另一个链接而不弹出模态。

现在,我正在尝试使用以下代码实现它

HTML:

<span id = "id1" ng-click="getClickType($event,row)" href=""> Text </span>

JS:

$scope.getClickType = function(event,row){
    $scope.activeElement = event.target;
    if(row.type == "A"){
        $scope.activeElement.dataset.target = "#ModalA";
        $scope.activeElement.dataset.toggle = "modal";
        /* Here I don't have to use the hack and the data target changes automatically and the modal pops up*/
    }
    else{
        someFunction().then(someOtherFunction);
    }
}

someOtherFunction(msg){
    if (msg.varA == true){
        var f1 = $scope.activeElement.dataset.target; //hack
        $scope.activeElement.dataset.target = "#ModalB";
        $scope.activeElement.dataset.toggle = "modal";
        if( f1 != $scope.activeElement.dataset.target){ //hack If statement
           $timeout(function () {
                            $scope.activeElement.click();
                       });
           /* Here i have use a hack and click on the element again to show the modal*/
        }
    }
    else{
        $scope.activeElement.dataset.target = "";
        $scope.activeElement.dataset.toggle = "";
        window.open(someURL);
        /* works fine*/
    }
}

所以你可以看到,我正在使用ModalB的黑客攻击。更改someOtherFucntion()中的dataset.target不会弹出模态。我必须再次点击活动元素才能显示。 我的问题是: 为什么我需要再次单击activeElement来更改数据目标。 为什么只在第二个功能中需要它。

任何帮助将受到高度赞赏。

提前致谢。

javascript angularjs twitter-bootstrap
1个回答
0
投票

someFunction发生了什么?这是一个像承诺一样的角度$ q或$ http?您是否尝试在$ scope中执行modalB内容。$ apply function?

当您意外地离开角度范围或执行非角度脚本时,有一个技巧

$scope.$apply(function() {
    $scope.activeElement.dataset.target = "#ModalB";
    $scope.activeElement.dataset.toggle = "modal";
 }

或者您可以在打开ModalB后立即调用$ scope。$ apply

$scope.activeElement.dataset.target = "#ModalB";
$scope.activeElement.dataset.toggle = "modal";
$scope.$apply()

这将迫使角度执行摘要并进行检查。但是这里有一个陷阱,如果你处于角度上下文中它可能已经在执行摘要循环,它会抛出一个错误,通知你这个过程已经在进行中,所以你的错误就在其他地方。

© www.soinside.com 2019 - 2024. All rights reserved.