JavaScript calls Angularjs's functions/$scope/variables

Source: Internet
Author: User



Use the background:



You need to call Angularjs internal methods or change $scope variables in other JavaScript files, while maintaining bidirectional data binding;



First Get ANGULARJS application:



Method One: Use the controller to get the app


 
var appElement = document.querySelector(‘[ng-controller=mainController]‘);


Then get the $scope variable:


 
var $scope = angular.element(appElement).scope(); 


If you change the variables, you need to show them on the page, and you need to call the Apply () method:


$scope. $apply ();


Method Two: Get the app through DOM manipulation


 
1 / / get the app object through DOM operation
2 var element = angular.element($document.getElementById("app"));
3 / / get the app object and the controller of the app
4 var controller = element.controller();
5 / / get the app object. You can get the $scope of the app
6 var scope = element.scope();
7 / / call the method in $scope
8 scope.sub1();
9 / / after calling the method, you can rebind it and synchronize it on the page (optional)
10 scope.$apply();
11 / / call field
12 scope.field1;


Several related functions:



Gets the current element's $SOCPE: angular.element (domelement). Scope () to get the present scope for the element
Get the current app's injector: angular.element (domelement). Injector () to get the present app injector
Gets the controller for the current element:angular.element (DomElement). Controller () to get a hold of the Ng-controller instance.



Reference article:



http://segmentfault.com/a/1190000000747708



http://longqiang.name/2014/12/13/%E5%A4%96%E9%83%A8js%E8%B0%83%E7%94%A8angularjs%E5%86%85%E9%83%A8%E6%96%B9%E6%B3%95/






JavaScript calls Angularjs's functions/$scope/variables


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.