Click event not triggered when transitioning to Service section in Thinkster tutorial

I've been following a tutorial on MEAN stack development () and I encountered an issue after incorporating Angular Services. For some reason, the function incrementUpvotes stopped working and I'm struggling to identify the cause. Since I'm relatively new to Angular services, I'm unsure if I initialized them correctly or if there's another underlying problem.

Any assistance would be greatly appreciated!!!

index.html

<html>
<head>
  <title>Flapper News</title>
  <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
  <script src="app.js"></script>
  <script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.10/angular-ui-router.js"></script>
  <style> .glyphicon-thumbs-up { cursor:pointer } </style>
</head>
<body ng-app="flapperNews">
  <div class="row">
    <div class="col-md-6 col-md-offset-3">
      <ui-view></ui-view>
    </div>
  </div>

  <script type="text/ng-template" id="/home.html">

    <div class="page-header">
        <h1>Flapper News</h1>
      </div>

      <div ng-repeat="post in posts | orderBy:'-upvotes'">
        <span class="glyphicon glyphicon-thumbs-up"
          ng-click="incrementUpVotes(post)"></span>
        {{post.upvotes}}
        <span style="font-size:20px; margin-left:10px;">
          <a ng-show="post.link" href="{{post.link}}">
            {{post.title}}
          </a>
          <span ng-hide="post.link">
            {{post.title}}
          </span>
        </span>
      </div>

      <form ng-submit="addPost()"
        style="margin-top:30px;">
        <h3>Add a new post</h3>

        <div class="form-group">
          <input type="text"
            class="form-control"
            placeholder="Title"
            ng-model="title"></input>
        </div>
        <div class="form-group">
          <input type="text"
          class="form-control"
          placeholder="Link"
          ng-model="link"></input>
        </div>
        <button type="submit" class="btn btn-primary">Post</button>
      </form>

  </script>
</body>
</html>

app.js

var app = angular.module('flapperNews', ['ui.router']);

app.config([
'$stateProvider',
'$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {

  $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: '/home.html',
      controller: 'MainCtrl'
    });

  $urlRouterProvider.otherwise('home');
}]);

app.factory('posts', [function(){
    var o = {
        posts: []
    };
    return o;

}]);

app.controller('MainCtrl', [
    '$scope',
    'posts',
    function($scope, posts){
        $scope.test = 'Hello world!';
        $scope.posts = posts.posts;
        $scope.posts = [
            {title: 'post 1', upvotes: 5},
            {title: 'post 2', upvotes: 2},
            {title: 'post 3', upvotes: 15},
            {title: 'post 4', upvotes: 9},
            {title: 'post 5', upvotes: 4}
        ];

        $scope.addPost = function() {
            if(!$scope.title || $scope.title === '') { 
                return; 
            }
            $scope.posts.push({
                title: $scope.title,
                link: $scope.link, 
                upvotes: 0
            });
            $scope.title = '';
            $scope.link = '';
        };
        $scope.c = function(post) {
            post.upvotes += 1;
        };
    }]);

Answer №1

Just a couple of points to note.

Initially, data is being imported from a service and immediately replaced with hardcoded values:

    $scope.posts = posts.posts;
    $scope.posts = [
        {title: 'post 1', upvotes: 5},
        {title: 'post 2', upvotes: 2},
        {title: 'post 3', upvotes: 15},
        {title: 'post 4', upvotes: 9},
        {title: 'post 5', upvotes: 4}
    ];

In response to your specific query, the ng-click directive mentions a function named incrementUpVotes(post), indicating it should be defined on the controller as $scope.incrementUpVotes. It appears that you did create this function but mistakenly named it $scope.c. Simply change it to $scope.incrementUpVotes and all should work smoothly.

    $scope.incrementUpVotes = function(post) {
        post.upvotes += 1;
    };

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

Angular binding for selecting all data

Upon checking a checkbox for a single item, the bound data is retrieved and added to an array. However, this does not happen when using selectAll. Code snippet in Angular for obtaining the object of a checked item: $scope.selectedOrganisations = []; $sco ...

When trying to reference "this" and store it in a variable, it appears as undefined. However, DevTools show that it is actually defined

I've encountered an unusual situation in my React app involving the binding of "this" - I have a function within a component named "App" that is located in a separate file. In the main file, I've bound the "this" command to it. What's puzzl ...

Working with AngularJS: Utilizing the Ng-repeat directive for iterating

I am struggling to figure out why the following code is not functioning properly. <div ng-repeat="r in reservations" ng-init="new = r.some_code"> <div ng-if="old == new"> <p ng-init="sum = sum + r.cost">{{r.name}} - {{r.cost}}</p&g ...

Formik's handleSubmit function appears to be malfunctioning

I have encountered a puzzling issue with Formik implementation in my two components. Despite implementing Formik in the same way for both components, I am facing a problem where `handleSubmit` works in one component but not in the other. You can check out ...

utilizing Typescript object within an array of objects

How can I optimize typing this nested array of objects? const myItem: Items[] = [{ id: 1, text: 'hello', items: [{ id: 1, text: 'world' }] }] One way to approach this is by using interfaces: interface It ...

Are you looking to refresh the Amplify Redirect URL?

Is there a way to update the redirection URI for Amplify signout in the 'aws-exports' file? What steps should be taken to make this change? Can we simply modify the file directly and then execute 'amplify push'? Update After attempti ...

Having trouble using functions with dynamically loaded content via AJAX in JQuery

I am facing an issue with my code. I am trying to dynamically fetch some data and display it. I have checked the request using firebug and it seems to be successful, but the problem arises when I try to execute the activeImage() function. The images are no ...

Delineating the execution of a PHP function through a button click using HTML/Javascript

I have a need to trigger a specific PHP function by simply clicking on a button. Currently, I am working with the following code snippet: <table class='standardtable'> <tr> <th>Event</th> <th>Group</th> ...

Is there a way to display two words side by side in React components?

I previously had the following code: projectName: project.get('name') === 'default' ? 'No Project' : project.get('name') In the render() method, it was written like this: <div className='c-card__projects&ap ...

Switching back and forth between fluid text fields

Is there a way to navigate between dynamically generated textfields using an iterator from struts-tags? <s:iterator value="aList"> <td width="50px" align="center"> <s:textfield name="solField" size="2" maxlength="1" style="text-transform ...

Can you explain which variable is considered global in Node.js?

Instead of writing var global = window for the browser I want my code to be able to work in a node environment as well. Something like var global = window || node_global What is node_global? I couldn't find any clear answer here: or here https ...

Unable to load Google Maps API in Angular: Error - Google Maps API is not accessible

Just starting out with Ionic app development and I decided to incorporate angular google maps using bower. bower install angularjs-google-maps After installation, I added the necessary reference files in my index.html file: <script src="lib/lodash/di ...

Navigating through root and sub applications within AngularJS can be managed effectively when housed in sub directories

I currently have two AngularJS applications in place: The first application serves as the base and operates at the root / The second application is a sub-application that needs to be isolated for design purposes, running within a subfolder such as /foo/ ...

Vue JS console displays an error stating "the <li> tag is missing a closing tag."

Below is the code snippet I am currently using to change the color based on the character's name: I encountered an error indicating that the li tag was not properly closed, although it appears to be closed. However, there seems to be an issue during ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

What is preventing the listener from activating?

I came across some HTML code that looks like this: <form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post"> <input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения"> ...

Properly configuring the root directory to troubleshoot Axios 404 POST issues within a Vue Component coupled with Laravel

As I delve into learning Vue+Laravel through a tutorial, I have encountered an issue with Axios when making an Ajax request within the script of a Vue Component. The console log error that is troubling me reads as follows: POST http://localhost/favori ...

Securing your Angular application with user authentication and route guarding ensures

In the process of developing an Angular single-page application (SPA) front-end that interacts with a GraphQL endpoint, I encountered a challenge. Upon user login, I store the token in local storage and update the authentication state in my AuthService com ...

Is there a way in Angular to activate the contenteditable feature through a controller?

I have a collection of items, and the currently selected one is displayed in more detail on another section of the screen. The detailed section allows users to modify specific parts of the chosen item using contenteditable. When a user adds a new item to ...

Access a designated tab within a CSS-designed tab system

Can anyone offer some assistance? I currently have a tab structure created using CSS. The first tab is set as the default when the page loads. I am looking to create a link from another page that will take users directly to the page with the tabs and ope ...