Tips for updating the value of an element in AngularJS using a function

HTML:

<div data-ng-app="story"  data-ng-init="detail='share your story here'">


<div data-ng-controller="detail_controller">
    <input type="text" name="detail" data-ng-model="detail">
    <h1>{{detail}}</h1>
    <input data-ng-click="submit_detail(detail)" type="submit" name="submit_detail" value="Share detail">


    <!--detail dashboard-->
    <div ng-model = "detail_dashboard" data-ng-show = "detail_dashboard.show">

        <div><h1 data-ng-model = "title" class="title">detail: {{title}}</h1></div>
        <div data-posted-answers></div>
    </div>
</div>

</div>

Angular js

var app = angular.module('story', []);


function addNewStory(data) {
    console.log('addNewStory called '+data);

how can I update the value in this function?

    $rootScope.title = 'new value';
}

app.controller('detail_controller', function($scope) {


    $scope.detail_dashboard = {
        show : false
    };

    $scope.submit_detail = function($value) {

        $scope.detail_dashboard = {
            show : true
        };

        $scope.title = $value;

        addNewStory($value);

    };



});

$scope and $rootScope give an error when used inside addNewStory() function:

ReferenceError: `$rootScope` is not defined

How do I change the value of any element within a controller? In jQuery, you simply target the element by its name, id, class or data attribute. But in AngularJS, how can I achieve that?

I also attempted this method:

angular.element('title').text('something new');

But it resulted in a jqLite:nosel error

Fiddle: https://jsfiddle.net/hadfgy4r/

Answer №1

Here is the perfect solution you've been searching for: https://jsfiddle.net/abc123xyz/3/


        var app = angular.module("storyApp", []);
        //Attempting this won't work as it's outside of the "Angular realm"
        /*function updateView(data) {
            console.log('updateView triggered '+data);
            $rootScope.heading = 'test';
        }*/

        app.service("myUpdater", ["$rootScope", function($rootScope) {
            this.updateView = function(data) {
                console.log('updateView triggered ' + data);
                $rootScope.heading = 'test';
            };
        }]);

        app.controller("detailController", ["$scope", "myUpdater", function($scope, myUpdater) {
    
        $scope.description = "Add your story here";
        
        $scope.viewDetails = {
            display: false
        };

        $scope.submit_detail = function(value) {
            $scope.viewDetails.display = true;
            
            $scope.heading = value;

            myUpdater.updateArticle(value);
        };
        
    }]);

Additionally, there seems to be an issue in your HTML code. The ng-model attribute is only suitable for inputs!

<div><h1 class="heading">display: {{title}}</h1></div>
    <div data-answered-posts></div>
</div>

Therefore, using ng-model in this context doesn't serve a purpose.

<div><h1 class="heading">display: {{title}}</h1></div>

Answer №2

It appears that the scope() and $apply functions are necessary in this situation. However, using jQuery is required. If there is a way to modify the code below without relying on jQuery, please inform me.

function updateArticle(data) {
var scope = angular.element($("#pquestion")).scope();
    scope.$apply(function(){

        scope.detail_dashboard= {
            show : true
        };

        scope.title= data;
    });
}

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

Converting PHP variables to JavaScript variables: A step-by-step guide

I'm trying to figure out the most efficient method for retrieving PHP variables using AJAX and then transforming them into JavaScript variables. Imagine I have the following code in my PHP file: echo $total; echo $actual; Edit: JSON echo json_enco ...

Using JavaScript, generate ten clickable circles on the screen. Each circle should display the number of times it has been clicked in the center when interacted with

I am currently working on my JavaScript skills and would like to implement a fun project involving 10 colorful circles. While I can easily create these circles using HTML and CSS, I require assistance with the interactive functionality using JavaScript. ...

Is there a way to use jQuery to toggle a child element when the parent is clicked?

There are three images displayed on a webpage, each accompanied by a list of three events. The desired functionality is that when a user clicks on an event, the corresponding information should be displayed below that event. Below is the HTML structure: & ...

I'm trying to use Javascript to dynamically remove rows, but my code seems to be causing some issues

When a user enters text into a form, it is stored in a variable called 'userInput'. I have an HTML table with the ID "myTable". My goal is to use JavaScript to iterate through the table and remove all rows where the value of the 3rd column does n ...

How to retrieve the index number of a clicked tab in Bootstrap 4?

I'm currently working on identifying the index of the tab clicked by the user within a group of tabs. For example, if there are five tabs and the user clicks on the second one. To calculate the total number of tabs, I can assign an ID to the navigati ...

The connection between React-redux @connect is malfunctioning, whereas using connect() functions smoothly

Is there an issue with using the @connect() syntax instead of export default connect()? It seems that when I stick to the traditional syntax class PhonePage extends Component { ... } export default connect(state => ({ testedByPhone: state.pho ...

Conceal a specific div element using jQuery hide method based on its unique

I'm facing a challenge with this code snippet. I am dynamically generating elements on a webpage from an array: $cars = array("Volvo", "BMW", "Toyota"); foreach($cars as $item) { echo '<div class="column col-3" id="'.$item.'" ...

Receive and process messages from RabbitMQ in a Node.js application

I am currently working on consuming messages from RabbitMQ in Node.js and so far, everything is going smoothly. During the message consumption process, I am performing some operations (such as API calls). Now, my goal is to only acknowledge the message o ...

Unable to retrieve value 'includes' from null object

Currently, I am utilizing Vue.js along with JavaScript. In my code, there is an array of objects named products, each containing a special property called smallest_unit_barcode. My goal is to filter out only those products that have a barcode similar to a ...

Slerping with quaternions in Three.js can produce undesirable outcomes when near the poles

Check out this video example: https://drive.google.com/file/d/18Ep4i1JMs7QvW9m-3U4oyQ4sM0CfIFzP/view In the demonstration, I showcase how I determine the world position of a ray hitting a globe under the mouse cursor. By utilizing lookAt() with a THREE.Gr ...

How to pass a variable or value through the async await API in the Vue.js and Laravel integration?

I'm facing an issue with my API where I want to check if a given email exists in the database, but every time I run it and view the console log, it returns undefined. Can anyone here suggest a better code snippet or approach for this? I specifically w ...

How to include additional custom attribute in a jQuery FormBuilder

Currently, I am utilizing jQuery FormBuilder from and I am in need of a custom attribute in the form of a Checkbox for each type. Whether it is a textarea, text input, checkbox, or any other type, I would like to consistently include the same checkbox as ...

Guide on establishing a connection to a server from a local database

Attempting to access an external database locally through my server, I ran the following code on the server side: console.log('MONGODB_URI_LOCAL::', config.MONGODB_URI_LOCAL) const mongooseLocal = require('mongoose'); const connectionO ...

Enhance your website's accessibility by using JavaScript to allow the down and up arrow keys to function

Thank you for taking the time to read this, any feedback is greatly appreciated. The current script on my website is only partially functional (click "i" in the bottom right corner). Currently, the script will focus on the first link AFTER pressing the T ...

JavaScript failed to execute

I am trying to make the JavaScript function execute when the subcat-tab class is clicked, but for some reason it's not working. There are no error messages showing up, but nothing is happening. This is within a phtml file in Magento 2. <a href=&qu ...

How do you implement radio button logic within an *ngFor loop?

When I populate options in a form with radio buttons, I am not seeing isChecked set to true when I select an option. Am I missing something in the following Angular code? app.component.html <div class="form-group"> <label>answerOption</la ...

Tips for uploading images in Next.js using Firebase

While following a tutorial on Next.js, I encountered an issue with the outdated version of Firebase being used. Despite trying different solutions from the documentation and various sources, I am still facing an error message while attempting to upload ima ...

Enhance data granularity in Jquery Flot by zooming in as the user interacts

I'm currently working on creating an interactive chart that allows users to zoom in for a more detailed view of the data. For instance, when viewing data over a default zoom period of 3 months, there would be one data point displayed every 24 hours. H ...

Guide on incorporating `Animate.css` into an Angular application

I've been attempting to implement the bounceInUp animation from animate.css on a div upon showing it, but I can't seem to get it to work. What am I doing wrong? Can someone guide me on the correct way to achieve this effect? This is my CSS code ...

Converting Epoch timestamp to AM/PM format in a React render function

I am currently working on a personal project using React.js. I have successfully fetched an API, and one of the values returned is an Epoch timestamp. My goal is to display this timestamp in a human-readable format such as am/pm. The Epoch timestamp is dis ...