Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - Access Angular object's function from outside JS

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 to work.
This is the Angular-object (function I need to access is the $scope.info()):

function content($scope) {
    $scope.info = function (id) {
        console.log('Got a call from '+id);
        $scope.text = "Hello, "+id;
    };
}

I have attempted to access it through angular.element('content').scope().info('me'), but with no result (console says undefined). I attempted to dump the result of angular.element('content').scope(), and I got the full object list and everything. Theoretically, my first example should work, however it does not.

Any guidance as to how I can achieve this is much appreciated!
(PS: Call Angular JS from legacy code did not resolve this).


When I was finally able to access the function, it didn't work as expected – the value of $scope.text is technically modified, but the expressions used in the HTML are not updated! For example, <p>{{text}}</p>does not get updated after this function is called from an external function.

Is there any way to fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...