【问题标题】:Change data target through Javascript通过 Javascript 更改数据目标
【发布时间】:2017-12-18 22:14:08
【问题描述】:

我正在开发一个 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 的 hack。更改 someOtherFucntion() 中的 dataset.target 不会弹出模式。我必须再次单击活动元素才能显示。

我的问题是:
为什么我需要再次点击activeElement才能更改数据目标。
为什么只需要在第二个函数中。

任何帮助将不胜感激。

提前致谢。

【问题讨论】:

    标签: javascript angularjs twitter-bootstrap


    【解决方案1】:

    someFunction 中发生了什么?它是一个像promise的angularjs吗? $q 还是 $http? 您是否尝试在 $scope.$apply 函数中执行 modalB 的东西?

    当你不小心退出 Angular 范围或执行非 Angular 脚本时有一个技巧

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

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

    【讨论】:

    • 嗨,在 someFunction 中,我从数据库中调用一个存储过程,然后返回一个带有结果集(msg)的 promise 给 someOtherFunction。您能否向我解释一下“您是否尝试在 $scope.$apply 函数中执行 modalB 的东西”?我怎样才能做到这一点? -谢谢
    • 另外一件事,这个promise是由$http处理的吗?如果没有,我建议用 $q.when 方法包装这个承诺:docs.angularjs.org/api/ng/service/$q#when
    • 嗨,它正在由 $http 处理。我无法进行任何更改,因为它被应用程序中的所有控制器使用。我尝试在 $scope.$apply 下运行语句,并且在更改数据集目标后还运行了 $scope.$apply 但无济于事。即使我正在使用 hack,我也只是想了解它为什么会发生。
    • 我为此创建了 plunker,你能帮我破解它吗? plnkr.co/edit/WIhYoe?p=preview
    猜你喜欢
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    相关资源
    最近更新 更多