Access Angular object's function from outside JS

后端 未结 2 709
醉梦人生
醉梦人生 2020-12-17 02:49

I\'m building a HTML-app with the AngularJS framework. I have some legacy JavaScript actions that needs to access a function within the Angular-object, and I can\'t get it t

相关标签:
2条回答
  • 2020-12-17 03:11

    For me, I was trying to access/set angular's values from a callback (in another Window); the solution was to use jQuery's data methods. The data API allows you to attach object literals to DOM nodes. So instead of resorting to something like global variables (which would also work), I just do something like:

    /**
     * Listen to a global "lookupTemplate" event
     */
    $j(document).on("lookupTemplate", function(event, template) {
            $j(document).data("template", template);
            window.open("/callbackURL", 'Callback Window', 'status=0,toolbar=0,height=230,width=358');
        });
    
    /**
    * Callback from other window, to change template ID and name (it's global)
    * @param {String} template_id the ID for the selected template from the other window
    * @param {String} template_name the name for the selected template from the other window
    */
    function templateChosen(template_id, template_name) {
        var template = $(document).data("template");
        var appendedSelector = "[" + template.index + "]";
        $('[name="templateId' + appendedSelector + '"').val(template_id);
        $('[name="templateName' + appendedSelector + '"').val(template_name);
        // Update angular vars just in case
        template.id = template_id;
        template.name = template_name;
    }
    
    var app = angular.module("app", []).controller("ActionsController", function($scope) {
            $scope.actions = [];
            $scope.lookupTemplate = function(index) {
                $scope.actions[index].template.index = index;
                $(document).trigger("lookupTemplate", $scope.actions[index].template);
            }
        }
    );
    

    Where I increment the name attribute of each new action with the {{index}} helper, included in Angular.

    0 讨论(0)
  • 2020-12-17 03:14

    angular.element() expects a DOM element, so if you have this html:

    <div ng-controller="content">
    </div>
    

    and you want to access its DOM element, use an id:

    <div id="myDiv" ng-controller="content">
    </div>
    

    Then

    angular.element($('#myDiv')).scope().info('me')
    

    or without jQuery:

    angular.element(document.getElementById('myDiv')).scope().info('me')
    

    should work.

    Edit:

    If you changed something on the scope, you will probably need to use $apply():

    angular.element(document.getElementById('myDiv')).scope().$apply();
    
    0 讨论(0)
提交回复
热议问题