【问题标题】:How to call an angular controller function from within an iframe如何从 iframe 中调用角度控制器函数
【发布时间】:2016-01-12 18:11:00
【问题描述】:

我正在使用 iframe 在使用 Angular 的多步商店结帐表单中处理信用卡付款的 3D 身份验证。

身份验证完成后,我需要从 iframe 中调用一个函数以进行下一步。 iframe 与父窗口位于同一域中。但是,调用该函数时出现scope.showStep is not a function 错误。

我怎样才能做到这一点?

iframe 内容:

<script>
    var scope = parent.angular.element(parent.document.getElementById("checkout-form")).scope();
    scope.$apply(function () {
        scope.showStep('success!')
    });
</script>

结帐控制器:

(function () {
    angular
        .module('app.checkout')
        .controller('CheckoutStep', CheckoutStep);

    CheckoutStep.$inject = ['$scope', '$state'];

    function CheckoutStep($scope, $state) {

        $scope.showStep = function (message) {
            $state.go('checkout.step', { message: message });
        }
    }
})();

HTML:

<div ng-app="app.checkout" id="checkout-form">
    <div ui-view id="checkout-step></div>
    <script type="text/ng-template" id="checkout-step1">
        // template
    </script>
</div>

【问题讨论】:

  • 我建议使用postMessage 进行跨帧通信。
  • 我已经添加了说明 - iframe 和父级在同一个域上,所以我认为 postMessage 没有必要。

标签: javascript angularjs iframe


【解决方案1】:

代码实际上工作正常,但是我从页面中获取了错误的元素。我需要检索视图元素,而不是 app 元素,因为我使用的是 UI 路由器。

请注意,如果 debugInfoEnabled 设置为 false,则无法访问 scope()

<script>
    var scope = parent.angular.element(parent.document.getElementById("checkout-step")).controller ();
    scope.$apply(function () {
        scope.showStep('success!')
    });
</script>

【讨论】:

  • var 控制器应该是 var 范围
猜你喜欢
  • 1970-01-01
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-29
相关资源
最近更新 更多