Angular click directive

Exploring AngularJS and attempting to modify an example from a tutorial. I want the ng-init value to be equal to the value passed from a script function. How can I achieve this? Here's the code snippet:

<html>
    <body>
        <h2>AngularJS Sample Application</h2>
        <div ng-app="mainApp"  ng-controller="clickController">
            <p>Total click: {{  click.clickCounter() }}</p>
            <button ng-click="count = count+1" 
              ng-init="count=click.clickCounter()">Click Me!</button>
        </div>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
        </script>
    </body>

    <script>
        var mainApp = angular.module("mainApp", []);

        mainApp.controller('clickController', function($scope) {
            $scope.click = {
                count: 15,
                clickCounter: function() {
                    var foo;
                    foo = $scope.click;
                    return foo.count;
                }
            };
        });
    </script>
</html>

Currently facing an issue with passing the value of click.clickCounter() to ng-click.

Answer №1

The problem arises from the creation of a new variable count at the root of the scope.

Instead of $scope.click.count, the ng-init and ng-click directives are creating and updating $scope.count.

Here is the corrected code:

<button ng-click = "click.count = click.count+1" ng-init="click.count=click.clickCounter()">Click Me!</button>

Additional note: By adding {{count}} in your app, you can see the scope variable being created. Angular has the feature of automatically adding variables to the scope if they are defined in the view but not in the scope.

Another point to consider is that the ng-init directive is unnecessary since the count property of $scope.click is already initialized and has a value.

For more information, refer to the fiddle: http://jsfiddle.net/yjwskkat/

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

Is it possible to return an array of middleware from one middleware to another in Express JS?

Looking to display shop information through a route. The route setup is as follows: router.param('userId',getUserById) router.get("/store/:storeName/:userId?",isAuthenticated,getStoreDetail) My goal is to send different responses based ...

Rearrange the layout by dragging and dropping images to switch their places

I've been working on implementing a photo uploader that requires the order of photos to be maintained. In order to achieve this, I have attempted to incorporate a drag and drop feature to swap their positions. However, I am encountering an issue where ...

Tips for positioning a sticky div underneath a stationary header

I'm currently utilizing Bootstrap 4 for my project, and I am encountering an issue with maintaining a div that has the class "sticky-top" just below a fixed navbar. Despite attempting to use JavaScript to replace the CSS while scrolling, it hasn' ...

Running res.render in an asynchronous manner within an express application

My goal is to make this router respond asynchronously: var express = require('express'), router = express.Router(); router.get('/', function(req, res, next) { res.render('contact', { titleShown: true, title: & ...

Receiving inaccurate video duration when the input bar is modified

Initially, I am uncertain whether the issue stems from Javascript or CSS. The code in question involves displaying the corresponding video time when a user hovers over an input bar. The calculation utilized is as follows: ((user mouseX position / input wi ...

What is the best way to configure Jenkins to exclude or include specific component.spec.ts files from being executed during the build

Currently, I am facing an issue while attempting to include my spec.ts files in sonarqube for code coverage analysis. However, my Jenkins build is failing due to specific spec.ts files. Is there a way to exclude these particular spec.ts files and include ...

Insert HTML elements into nested CSS classes

My goal is to utilize jQuery for looping through classes and adding text to an HTML element. I am currently working with the following example HTML: <div class="question"> <div class="title"> <strong>Here's the question ...

What is the best way to determine if an object.property is defined in Angular 2?

Is there a similar function in Angular 2 to angular.isDefined from Angular 1? I have tried using the safe navigation operator ?., which is only supported in templates. ...

Guide on retrieving JSON information within an array utilizing a loop function

Hey everyone, I'm facing an issue and I could really use some help. I'm new to working with ajax processing and I'm stuck on a problem. I have successfully retrieved ajax data and now I need to store it in an array. My goal is to populate a ...

Switch the dropdown selection depending on the checkbox status

I'm currently facing a bit of confusion with my project. I am constrained by an existing framework and need to come up with a workaround. To simplify, I am tasked with populating a dropdown list based on the selected checkboxes. I have managed to get ...

The method for storing a user's choice in my array and subsequently selecting an element at random

Seeking assistance in developing a program that can play an audio list at various durations. The plan is to have the duration for elements 4 through 8 based on user selection, with the program playing each element within that range during the initial round ...

Rendering based on conditions with a pair of values

I am trying to render my component only if the id is equal to either 15 or 12. My current approach is not working as expected, it only renders the component when I check for one id at a time, but I need to check for both. {query_estate_id === 15 || q ...

Obtain image file paths dynamically in a folder using Nuxt

https://i.sstatic.net/3FKZH.png Incorporating nuxt with vuetify, I have successfully implemented a carousel component. Now, my goal is to generate a list of the .png files located in the static folder. By referencing a tutorial on dynamically importing im ...

Implement a jQuery slideshow with a full background image, aiming to set up a clickable link on the final image of the

Could someone please help me with a query I have regarding a background image slide show using jQuery code? I have set up a slide show with multiple images and would like to make the last image clickable. Is it possible to achieve this specific functionali ...

Issue encountered while attempting to include a background image in React JS

I encountered an issue when attempting to include a background image in react js. ./src/index.css (./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-4-1!./node_modules/postcss-loader/src??postcss!./src/index.css) Unable to locate module: An attem ...

Using the XMLHttpRequest object for AJAX file uploads that are compatible with Internet Explorer 9

Seeking help with uploading a file using ajax. The current code works on all browsers except for i.e 9 and older versions. I need to find a solution that will also work on i.e. Some suggestions have been to use an iframe, but I don't see how that res ...

The responseXML received from an Ajax/POST request is missing only when using Chrome browser

While working on a "simple" JavaScript application, I noticed an unusual behavior. A function in the script sends a request with parameters to a .php page using the traditional Ajax/POST method. function sendRequest(params, doAsync, onSending, onDone) { v ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

Is it possible to convert the text.json file into a jQuery animation?

Looking to extract information from text.json and integrate it with my jquery.animation(). My goal is similar to the one demonstrated here. Instead of using "data" attributes like in that example, I want to parse the text based on the "ID" property as a k ...

`Testing the functionality of javascript/jQuery events using Jasmine`

I came across this code snippet: $(document).on('click', '#clear-button', clearCalculatedPrice) clearCalculatedPrice = -> $('#price_rule').removeAttr('data-original-title') $('#calculated-price&apos ...