Search code examples
jqueryangularjscolorbox

Trigger scope functions from JS outside the controller


I've seen other responses to this on SO, but either I didn't understand how those responses worked in my situation or I'm overthinking this; scopes have always been a poor point of mine.

I'm currently using colorbox for modal windows, containing iframes. To use it in angular, I created an attribute directive that takes the URL of an anchor tag and uses it to trigger colorbox. Typically, when a user does whatever action I need in the modal, I've had JS trigger something in the parent window, to avoid reloading. This seems even more important in Angular, and I'm trying to figure out how I can have said colorbox modal communicate with Angular. So far, the best I can think of is to have the modal's JS change the value of an input (or multiple inputs) to define what I want it to do.

Is there any easier/more direct way?

EDIT: Thanks to the solution below, I found the answer:

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

The key is parent on the element elector AND before angular.element.


Solution

  • it s an angular question in my understanding.

    I think this question will help How to change AngularJS data outside the scope?

    As you can see in the fiddle available there http://jsfiddle.net/jeremy/kj8Rc/

    The change function is a global one, i mean not in the angular scope of execution.

    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; 
        });
    }