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

What is the best way to create a React component that renders a class component as a functional component?

My Objective: At the moment, I am in the process of developing an AuthUserRole HOC component to manage user roles like Manager and Employee. However, I encountered a tutorial that uses a functional component to return a class component as referenced here. ...

Executing Rake tasks on the live server fails because of an issue with ExecJS

I currently have a Rails 4 application running on a RHEL 6 server. The production environment utilizes Passenger and Apache2. Recently, I've been attempting to schedule Rake tasks in the production environment using the Whenever Gem and Cron. Howev ...

Discover the process of retrieving all workday dates using Angular

Currently, I am working on a project in Angular that involves allowing employees to record their work hours. However, I am facing a challenge in figuring out how to gather all the work dates and store them in an array. Here is what I have attempted so fa ...

Receiving information within an Angular Component (Profile page)

I am currently developing a MEAN Stack application and have successfully implemented authentication and authorization using jWt. Everything is working smoothly, but I am encountering an issue with retrieving user data in the Profile page component. Here ar ...

The Link Breaks the Overlay Hover Effect

Currently, the code functions as intended when you hover over or touch the thumbnail, an overlay will appear. The issue lies in the fact that to navigate to a specific URL, you have to click directly on the text. The overlay itself is not clickable and ca ...

Is it possible for two-way binding to function in index.html within Angular 4?

Does two-way binding function in index.html? I have some links and metadata in index.html. How can we define head parameters in a component? <head> <meta name="og:title" content={{titleValue}}> <meta name="og:url" content={{urlValue}}> & ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

Unspecified origins of Js in Chrome Extension

console.log(chrome.runtime.sendMessage({from:"script2",message:"hello!"})); However, attempting to send the message from a background script to a content script is proving to be unsuccessful. https://i.stack.imgur.com/ERgJB.png ...

Creating an interactive table with the power of FPDF and PHP

I have developed a unique Invoice System that allows users to customize the number of headings and fields using FPDF in conjunction with PHP. Subsequently, I can input the heading names and field values into HTML input fields. However, I am encountering a ...

Performing a password-protected JavaScript Ajax request that includes special characters

Within my JavaScript page, I have implemented an Ajax call shown in the code snippet below. The PHP page resides within a corporate intranet that demands domain authentication (without basic auth). To extract the username (u) and password (p), I am using j ...

Experiencing issues with transferring JSON response from Axios to a data object causing errors

When I try to assign a JSON response to an empty data object to display search results, I encounter a typeerror: arr.slice is not a function error. However, if I directly add the JSON to the "schools" data object, the error does not occur. It seems like th ...

Encountering issues with JSON.Parse in JavaScript leads to errors

I'm encountering issues with JSON parsing in my code and I can't figure out the cause of it. I have a function that calls two ajax functions, one at the start and another in the success function. Everything seems to be working fine until I try to ...

Assigned a gender to my _id using the first name and last name

Hello, I am attempting to generate an _id in mongodb using a combination of the first name and last name. However, I'm encountering a problem with this process. My desired format for the id is like this: '_id':'midoxnavas' where &a ...

Challenges with using the $filter('limitTo') function in AngularJS

Struggling with implementing the limitTo filter in JavaScript The angularjs docs for limitTo explain that the filter should be used as follows: $filter('limitTo')(input, limit, begin) It's important to note that the begin parameter is opt ...

Is it possible to disable the "super must be called before accessing this keyword" rule in babelify?

My current setup involves using babelify 7.2.0 with Gulp, but I've encountered an error when working with the following code snippet: class One {} class Two extends One { constructor() { this.name = 'John'; } } The issue at hand i ...

Update a single javascript variable on every rotation of the Bootstrap carousel

Within my website, I have implemented a popin/modal feature using Hubspot Messenger which includes a Bootstrap 3 carousel. Each slide of the carousel displays a different "social embed" such as Facebook or Twitter, and I am looking to adjust the width of t ...

What is the process for updating a placeholder text after the user makes a guess or enters

My latest project involves creating a fun guessing game where players have to identify the driver based on the teams they have driven for. The game displays the number of guesses allowed and keeps track of how many attempts the player has made so far. For ...

jquery's each method is not functioning as intended and causing unexpected issues

I'm in the midst of developing a website, and one section requires users to input their details into a form. My goal is as follows: When a user clicks the submit button with any empty fields, I want a span element (initially set to display none in CS ...

Ways to revert all modifications to styles implemented using JavaScript

Hey there, just checking in to see how you're doing. I was wondering if there's a way to reset all the styles that have been changed using JavaScript? I'm referring to the styles shown in this photo: Thanks in advance. ...

Generate a list of JS and CSS paths for UglifyJS/UglifyCSS by parsing an HTML file

Seeking a tool that can scan an HTML file (specifically a Smarty template file) to extract paths from <script></script> and <link/> tags for use with UglifyJS/UglifyCSS or similar minification tools. Extra credit if it can handle download ...