Using AngularJS in conjunction with other scripts

I am currently working on an application and now I have the task of implementing a dynamic menu using AngularJS. This requires me to modify variables in the AngularJS application from my existing code.

Here is the example I am experimenting with:

<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>

I am seeking guidance on the correct method to invoke the "resetName()" function from an external script. Any suggestions?

Answer №1

To access a controller function in AngularJS, simply attach a selector to the DOM element where your controller is defined. For example:

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

Once you have set up your controller like this, you can call its functions from anywhere using:

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

Alternatively, you can also use:

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

If you need to modify an object value within the controller, it's easy to do so by directly accessing it:

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

Remember to manually trigger the apply function after making any changes to the objects, as Angular will not do this automatically anymore:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: "AngularJS encountered a $injector:modulerr error in Internet Explorer 11."

I've successfully created an AngularJS App that functions properly on most browsers like Firefox, Opera, Safari, Edge, and Chrome. However, there seems to be a compatibility issue with IE 11. When attempting to open the app in IE 11, the following er ...

Simple method to toggle between elements using jQuery

After creating a script using jQuery to show/hide content when tabs are clicked (which also changes the color of the clicked tab), everything is functioning smoothly. However, I believe there may be a more efficient way to switch between content that allow ...

Exchange one HTML element with a different HTML element

I've been attempting to change an HTML tag using PHP or jQuery. The current default tag is: <li class="dropdown"> <a href="index.html" class="dropdown-toggle"> Home</a></li> My desired replacement for the above HTML tag is: ...

Tips for launching different web browsers via hyperlinks?

My app has a link that I want mobile users from apps like LinkedIn to open in a browser such as Safari. I attempted this: <a href="safari-https://meed.audiencevideo.com">May open on Safari</a>' However, when I click the link, it opens i ...

The webpage is not refreshing or reloading despite using window.location.href

When creating a refreshcart() function, the window.location.href is assigned to currentUrl. However, when making an ajax call in the else block with window.location.href = currentUrl, true; it does not successfully refresh the page. $(document).ready(fu ...

Next.js: Attempting to access properties of undefined (specifically, attempting to iterate over an undefined value using the 'map' method) in React.js (Next

Hello there, I need some assistance with an error that I am encountering. It seems to be unique to me as I'm following a course on YouTube and only I am facing this issue. Can anyone help me out? import Head from 'next/head'; import styles f ...

Retrieve data from two separate files and store it as a two-dimensional array in JavaScript

Is there a way to read and convert two .txt files into a 2d array? I currently have a code snippet that looks like this : var fs = require('fs') file = './text1.txt' fs.readFile(file,'utf-8', (e,d) => { textByLine = d.s ...

AngularJS: when only one line is visible, the other remains hidden

Issue with AngularJS: Only One Line Displaying Instead of Both I am encountering an issue with my AngularJS code where only one of the elements is displaying on my page. function Today($scope, $timeout) { $scope.now_time = 0; (function update() { ...

Utilizing AJAX for XML data parsing

I need help with formatting XML data into a table. The code I've written isn't working as expected. The XML data is structured in branches, causing it to not display correctly. Can someone assist me in fixing this issue? <!DOCTYPE html> &l ...

Adjusting picture dimensions with percentages in canvas and jquery

I'm currently working on a one-page project that involves a canvas where users can click to add or place images randomly. I have made progress with most of the functionality, but as a beginner in jquery and canvas, I am struggling to set a maximum siz ...

`There seems to be an issue with multiple markers not appearing on Google Maps when using AngularJS.`

.controller('homeCtrl', function($scope, Markers) { var username = window.localStorage.getItem('username'); var id_user = window.localStorage.getItem('id_user'); console.log(username); console.log(id_user); document.getElement ...

Establishing a minimum width for the value of zero in AmCharts column series by customizing the bullet labels

Here's an interesting example where I have arranged column series with bullet labels. However, you may notice that there are some 0 values present as well. My goal is to establish a minimum width for the series so that even if the value is small or 0, ...

Calculation Error in JavaScript/JQuery

I've been working on a JavaScript function to calculate the sum of values entered into textboxes, but it seems to be giving me inaccurate results in certain cases. Check out the FIDDLE here Enter values : 234.32 and 32.34 Result: 266.6599999999999 ...

Tips for displaying a loading indicator above a form

I've been struggling to figure out how to display a loading indicator on top of my form without messing up the styling... https://i.sstatic.net/FFCRW.png My goal is to show the loading indicator when any action, like deleting an item or changing qua ...

Having trouble connecting to the http json service in AngularJS

I recently started learning angularjs and I'm facing an issue with my code. There seems to be a flaw in the code and I'm uncertain about it. From a java perspective, the httpController has a nested function defined inside. Below is the code sn ...

What is the appropriate content-type to use when sending AJAX POST data?

Having an issue sending base64 image data using ajax post. I suspect the problem lies with the Content-Type value, as I have tried using application/json, text/json, and image/jpeg without success. Javascript function sendFormData(fD) { var urls = fD ...

Using react-select to display "N items selected" instead of listing out all the selected items

Exploring the potential of react-select as a city-picker selector for users to choose one or multiple cities to filter data. Take a look at how it appears on my page: https://i.sstatic.net/A3cBX.png The list of cities may be extensive, and I am concerned ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

The development chrome extension failed to load due to an invalid port or malformed URL pattern

I'm encountering an issue while trying to load my development chrome extension for debugging. The error message I am receiving is: Issue with 'content_scripts[0].matches[0]' value: Path cannot be empty. Manifest failed to load. This is th ...

Utilizing Redux Reselect for Comment Filtering

Currently, I am attempting to filter and showcase comments that have a matching 'postID' with the current post id. Utilizing Redux/Reselect, the functionality works well but occasionally an error pops up indicating that post._id is undefined/null ...