2

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?

1 Answer 1

7

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();
Sign up to request clarification or add additional context in comments.

10 Comments

@wutzebaer -- Along with this, if you ever need to test Angular functions in your console, you can use the above as well var z = angular.element('#myCtrl').scope(); z.resetName("Test Param");
@tymeJV totally agreed (y)
is it possible to change scope variables like this: angular.element('#topMenu').scope().title = "test"; - i tried but get an error: Error: [jqLite:nosel] errors.angularjs.org/1.4.2/jqLite/nosel
Just try angular.element(document.querySelector('#myCtrl')).scope().title = "test";
ok i found the two problems: 1: you have to wait for document.ready before you can access external, 2: the function is called $apply()
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.