Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...