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
163 views
in Technique[技术] by (71.8m points)

javascript - Call AngularJS from other scripts

application. Now i want to implement an dynamic menu with AngularJS. Therefore i need to change variables in the AngularJS application from my existing application.

I'm trying with this example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl" id="myApp">

  First Name:
  <input type="text" ng-model="firstName">
  <br>Last Name:
  <input type="text" ng-model="lastName">
  <br>
  <br>Full Name: {{firstName + " " + lastName}}
  <button ng-click="resetName()">hi</button>

</div>

<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
  $scope.resetName = function() {
    $scope.firstName = "John1";
    $scope.lastName = "Doe1";
  }
});

</script>

<button onclick="angular.element('#myApp').scope().resetName(); angular.element('#myApp').scope().apply();">extern</button>

what would be the correct way to call the "resetName()" function from an external script?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Just attach a selector to your DOM element where your controller is defined. like

<div ng-app="myApp" ng-controller="myCtrl" id="myCtrl">

and from anywhere you can call this controller function like

angular.element('#myCtrl').scope().resetName()

OR

angular.element(document.querySelector('#myCtrl')).scope().resetName()

In some case you need to modify a object value of controller you can do it in simple way. Just use

angular.element(document.querySelector('#myCtrl')).scope().title = 'test';

Note : Please don't forget to apply the changes because now angular will not trigger apply automatically. You need to trigger apply manually. Just put below line after updating values in object/s

angular.element(document.querySelector('#myCtrl')).scope().apply();

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

...