【问题标题】:Trigger scope functions from JS outside the controller从控制器外部的 JS 触发作用域函数
【发布时间】:2015-05-24 06:13:03
【问题描述】:

我在 SO 上看到了对此的其他回应,但要么我不明白这些回应在我的情况下是如何起作用的,要么是我想太多了;范围一直是我的一个弱点。

我目前正在为包含 iframe 的模态窗口使用颜色框。为了在 Angular 中使用它,我创建了一个属性指令,该指令采用锚标记的 URL 并使用它来触发颜色框。通常,当用户在模式中执行我需要的任何操作时,我已经让 JS 在父窗口中触发某些东西,以避免重新加载。这在 Angular 中似乎更为重要,我试图弄清楚我如何才能说颜色框模式与 Angular 进行通信。到目前为止,我能想到的最好的方法是让模态的 JS 改变一个输入(或多个输入)的值来定义我想要它做什么。

有没有更简单/更直接的方法?

编辑:感谢下面的解决方案,我找到了答案:

var appElement = parent.document.querySelector('[ng-app=gamersplane]');
var $scope = parent.angular.element(appElement).scope();
$scope.$apply(function() {
    // Do your angular stuff in here!
});

键是元素选择器上的父元素,并且在 angular.element 之前。

【问题讨论】:

    标签: jquery angularjs colorbox


    【解决方案1】:

    在我的理解中,这是一个角度问题。

    我认为这个问题会有所帮助 How to change AngularJS data outside the scope?

    正如你在小提琴中看到的那样http://jsfiddle.net/jeremy/kj8Rc/

    change 函数是一个全局函数,我的意思是不在执行的角度范围内。

    function change() {
        // here it fetches the mandatory, and unique (?tobeconfirmed) ng-app HTML element.
        var appElement = document.querySelector('[ng-app=myApp]'); 
        // it finds the scope for you, given that previous element, i believe it s root scope in that case as ng-app.
        var $scope = angular.element(appElement).scope();
        // it s kind of scope binding, it will execute this function within angular scope of execution
        $scope.$apply(function() {
            // then finally appply his change within angular scope of execution, doing so effectively apply the changes
            $scope.data.age = 20; 
        });
    }
    

    【讨论】:

    • 这看起来很棒,但没有奏效。如果我 console.log(angular.element(appElement).scope()),它返回 null,即使 console.log(angular.element(appElement)) 返回我有问题的元素,所以 apply() obv 不起作用。是因为我引用了父文档吗?就像我提到的那样,我正在尝试从 iframe 触发它。
    • 你好,你能确认产地是一样的吗? (DNS) 你有 jquery 加载吗? docs.angularjs.org/api/ng/function/angular.element。你能检查查询选择器的结果吗?是否可以用 fiddle 实现一个示例?我没有快速尝试如何使用它来管理 iframe。
    • 我看看 plunkr 是否支持 iframe 并试一试。但是,是的,两者都在同一个来源,jQuery 和 Angular 都加载了。查询选举器给了我一个元素。
    • 这是一个显示我遇到的问题的 plnkr:plnkr.co/edit/MpkpIDNYIztiB5tqOR3M?p=preview
    • 得到了解决方案;我正在编辑我的帖子以显示对您的代码进行的修改以使其正常工作。
    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 2013-11-28
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    相关资源
    最近更新 更多