Trouble with updating AngularJS $scope variables in the view

I am a beginner in Angularjs and I am facing an issue with updating two $scope variables using separate functions that are called on ng-click.

Although the variables get updated, they do not rebind in the view.

HTML

<div ng-app="">
<div ng-controller="MainCtrl">
     <p> <a href="#" ng-click="getDetails();getElse()">Refresh</a> </p>
    <p ng-controller="MainCtrl"><span ng-bind="something"></span></p>
       <p ng-controller="MainCtrl"><span ng-bind="somethingelse"></span></p>
</div>
</div>

JS function MainCtrl($scope) {

$scope.something = "something";
$scope.somethingelse = "else";

$scope.getDetails = function () {
     alert("getdetails before change: "+$scope.something);
    $scope.something = 'changed';
    alert("getdetails: "+$scope.something);
};

$scope.getElse = function () {
    alert("getElse before change: "+$scope.somethingelse);
    $scope.somethingelse = 'changed';
    alert("getElse: "+$scope.somethingelse);
    };

}

I have created a fiddle demonstrating my issue: http://jsfiddle.net/M3pZ8/

Any guidance on the correct approach would be much appreciated.

Thank you!

Answer №1

The reason for the issue is the declaration of MainCtrl three times, leading to the creation of multiple scopes. It should only be declared once at the beginning.

<div ng-controller="MainCtrl">
    <p> <a href="#" ng-click="getDetails();getElse()">Refresh</a> </p>
    <p><span ng-bind="something"></span></p>
    <p><span ng-bind="somethingelse"></span></p>
</div>

Answer №2

Check out the revised jsfiddle

 Avoid adding the same controller multiple times in your code.

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

Problem with JQuery draggable and droppable appending elements

I am looking to create a functionality where a div can be dragged into another droppable div and be contained within it, while still remaining draggable inside the droppable div. However, When I try to drag the div into the droppable area, it seems to be ...

Sharing data between the main component and the sidebar in React-Router

Currently working with Meteor in combination with React-Router, and this is the code I'm dealing with: Routes.jsx: Meteor.startup(() => { render( <Router history={browserHistory}> <Route path='/' component={App}> ...

What is the best way to transform this functioning JavaScript code into jQuery?

<script type="application/javascript" language="js"> function checkPasswordUpdate(value) { if(value === '1') { var nav = document.getElementById("sNav"); if(document.getElementsByTagName) ...

Effortlessly sending multiple values from text fields using jQuery

i am using jQuery to fetch all values from text fields with the same field name. $('input[name^="StudentName"]').each(function() { StudentName += $(this).val(); alert(StudentName); }); when I alert, all the values are displayed as one s ...

Performing a bulk upsert operation by utilizing the $in operator in the update criteria

As I create a procedure to handle an array of strings like var mywords = ["cat", "dog", "fish"] and insert them into the 'words' collection in MongoDb, I aim to keep track of the insertion count for each word. Some words may already exist in t ...

Developing a continuous running test loop

Currently, I have a code that runs fine, but I am looking to modify it to run in a loop that counts the number of elements with the class="socal" and tests each link. module.exports = { 'Unitel Fitness - click' : function (browser) { bro ...

Comparison between forming JavaScript objects using arrow functions and function expressions

What is the reason behind const Todos = function () { ... } const todos = new Todos(); running smoothly, while const Todos = () => { ... } const todos = new Todos(); results in a TypeError: Todos is not a constructor error? ...

Execute the function when the form is submitted and show the total of the two values

I am currently working on a straightforward custom module for Drupal 7. This module takes two numeric values and upon submission, displays the sum of these values on the same page. While I have the form set up, it is not yet complete. I am facing some dif ...

React Native app utilizing Expo can successfully import local databases in a web view, but encounters issues when attempting to do so on smartphones

I created a small learning app and imported data from a local database using the following code: import { StatusBar } from 'expo-status-bar'; import { Platform, FlatList, StyleSheet, Text, View, TextInput, Button, SafeAreaView, ScrollView } from ...

What are some techniques for emulating resizing functionality in Angular?

Is there a way to simulate resize in Angular without using jQuery? In the past, I used the following code: $(window).resize(); I also have a question about focusing on an element: angular.element(document.querySelector('.kb-active')).focus(); ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

Can text be inserted into an SWF file using ASP.NET or Javascript via an online platform?

I am managing a website that features videos created by a graphic designer who updates and adds new content regularly. I am looking to add dynamic text to these videos after a specific amount of time, such as "Hosted by XXX". However, I am hesitant to ask ...

A step-by-step guide on sending a fetch request to TinyURL

I have been attempting to send a post request using fetch to tinyURL in order to shorten a URL that is generated on my website. The following code shows how I am currently writing the script, however, it seems like it's not returning the shortened URL ...

Is there a way to download a file using an ajax request?

We are faced with a particular scenario in our application where: Client sends a request Server processes the request and generates a file Server sends the file back as a response Client's browser prompts a dialog for downloading the file Our appli ...

Determining when a checkbox changes state using HTML and JavaScript

My main objective is to display divX2 when the checkbox for x2 is checked, either by directly clicking on x2 or by clicking on the "Check All" checkbox. The functionality works as intended when the checkbox for x2 is clicked, but it fails to work when the ...

Tally the number of words entered in the text box

Is there a way to make the keyword search in a text area live, rather than requiring the user to manually initiate the search? I have a working code that counts the number of times a specific keyword is used within the text, but it currently requires the u ...

Change a Python string in the format 'min:sec' into a time object so it can be displayed correctly and sorted by the jQuery tablesorter

Currently, I am facing an issue where tablesorter is only working correctly on string representations of time that are below '25:00'. Any values above this are being sorted lower than strings like '24:12' or '09:24'. It seems ...

The storage functionality in this session is malfunctioning

Take a look at this code: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication3.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> < ...

Issues with AngularJS version 1.8.0 and the ng-selected option functionality not functioning as

I recently updated the AngularJs version from 1.4.8 to 1.8.0 and encountered an issue with ng-selected on a select element that requires a default value. Can anyone provide guidance on how to set ng-selected in version 1.8.0? (the code utilizes ng-model) ...

Incorporate Bookmarklet into GitHub README.md

Trying to add a Bookmarklet to a Github README.md, but encountering issues with the markdown code: [Bookmarklet](javascript:alert('not-working')) It appears that the javascript in the link is being stripped out from the compiled output. Is this ...