How can I implement the vm. syntax using ControllerAs in my application?

After reading various sources, including a few discussions on Stack Overflow, I have come to understand that the ControllerAs syntax is gaining popularity as it aligns with how things are done in Angular 2.

Therefore, I decided to delve deeper into understanding how the syntax with vm. works.

Regardless of personal opinions on this approach, I am interested in pointers on why this method may not be effective,

//controllerAs with vm. syntax
var app = angular.module('myApp', []);

app.controller('MyCtrl', function () {

  var vm = this;
  vm.like = likeIt;
  vm.dislike = dislikeIt;
  vm.flag = flagIt;

    function likeIt() {
      alert('liked');
    },
    function dislikeIt() {
      alert('disliked');
    },
    function flagIt() {
     alert('flagged');
    }

});

Plunkr 1

compared to using $scope as shown below:

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

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

 $scope.like =  function () {
      alert('liked');
    };
  $scope.dislike =  function () {
      alert('disliked');
    };
  $scope.flag =  function () {
     alert('flagged');
    }

});

Plunkr 2

HTML

<html ng-app="myApp">

      <head>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
        <script src="script.js"></script>
      </head>

      <body ng-controller="MyCtrl as vm">
        <button ng-click="vm.like()">Like</button>
        <button ng-click="vm.dislike()">Dislike</button>
        <button ng-click="vm.flag()">Flag</button>

      </body>

    </html>

Answer №1

To solve this issue, follow these steps:

ng-controller="MyCtrl as action"

Then, make sure to use it in the following way:

ng-click="action.like()"

If you don't do this, Angular will not recognize the functions.

Another problem is that there are extra commas after the first two functions, which can cause the code to break:

function likeIt() {
  alert('liked');
}, <-- This one
function dislikeIt() {
  alert('disliked');
}, <-- And this one
function flagIt() {
 alert('flagged');
}

For a working example, check out this Plunkr: http://plnkr.co/edit/R7oTvcUxjCqi8YXoLOoh?p=preview

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

Encountering an issue while attempting to utilize $resource in AngularJS

Here is the code I have been working on: http://plnkr.co/edit/2blxwwyv0gS9GYui7IVn?p=preview In my project, I defined a service as follows: angular.module('jsonService', ['ngResource']).factory('JsonService', function($resou ...

Utilizing Unix timestamps for x-values while displaying dates as x-labels in an ECharts line chart

I'm struggling with incorporating date-converted unix timestamps as values in my ECharts graph. The x-axis of my chart is meant to display the recording time for each buy or sell price, represented by respective lines. Everything functions properly wh ...

Creating an array dynamically by parsing a JSON object in Javascript

I am currently working with a JSON object that looks like this: var testJSON = [ { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_c", "AssetB": "asset_d" }, { "AssetA": "asset_c", " ...

Displaying a momentjs object within Angular templates

Looking to display a momentjs object, not an ISO8601 string, in AngularJS templates. For example: $scope.time = moment(); When I try the following in my template: <span ng-bind="time"></span> or <span>{{time}}</span> I want to ...

Error: VueQuill Vue3 encountered an issue while trying to read properties of undefined with the message "emit"

Incorporating VueQuill into my vue3 application is resulting in the following console error when attempting to display an HTML string - https://i.stack.imgur.com/KGQqD.png This is my code snippet: <template> <div class=""> & ...

Ways to develop a dynamic HTML TransferBox featuring a custom attribute

I am in need of developing a customized transferbox using HTML, JavaScript, and JQuery. The user should be able to select from a list of options and associate them with attributes. This selection process should involve transferring the selected options be ...

Why does my React.js application still display outdated data from my Express server even after refreshing the webpage?

I have been working on a website using React.js and Express.js, following an online example to set up the basic code. I encountered an issue where the frontend did not update when I made a minor change to the array sent by Express.js. Express - users.js f ...

What is the method for performing a spelling check on every property within an array of Objects?

I'm working on a program that takes a user input as an argument and then searches for a similar match in an array of objects. The array of objects is retrieved from a database. When the user inputs a name, the search criteria should find objects with ...

Modifying the default label for each bubble on a bubble chart with chartjs-plugin-datalabels

Is there a way to add labels to each bubble in the bubble chart using chartjs-plugin-datalabels? For every bubble, I'd like to display the label property of each object within the data.dataset array, such as "Grapefruit" or "Lime". Currently, I'm ...

Using v-model in Vue 3 will result in modifications to the table class in Bootstrap 5

Below is a snippet of the code I wrote: <table class="table table-striped"> <tr class="table-dark"> <th>#</th> <th>Column 1</th> <th colspan="3">Column 2</th> </tr> <tr ...

Stop useEffect from triggering during the first render

I'm working on implementing a debounce functionality for a custom input, but I'm facing an issue where the useEffect hook is triggered during the initial render. import { useDebouncedCallback } from "use-debounce"; interface myInputProps { ge ...

Rails Ajax issue encountered

I previously followed a coderwall tutorial on ajax but encountered an ActionController::UnknownFormat error when attempting to open the link in a new tab (Link Name). Can anyone help me figure out what's wrong? Thanks! Additionally, clicking the link ...

NodeJS loop issue with variable scoping in the context of express and mongoose

My Tech Stack: NodeJS, express, mongoose var i; for(i = 0; i < results.length; i++){ console.log("out: "+i); RegionData.findOne({'rid': results[i].region_id}, function (err, product) { if (product) { console.log("i ...

Attempting to initiate an AJAX request to an API

Hey everyone, I've been working on making an AJAX API call to Giphy but I keep receiving 'undefined' as a response. Can anyone offer some advice on how to troubleshoot and fix this issue? Thanks in advance for your help! var topics = ["Drak ...

Leveraging PapaParse for CSV file parsing in a React application with JavaScript

I am encountering an issue with reading a CSV file in the same directory as my React app using Javascript and Papaparse for parsing. Below is the code snippet: Papa.parse("./headlines.csv", { download: true, complete: function(results, f ...

Unable to access account: HTML Javascript login issue

Problem with Login Code As a newcomer to HTML, CSS, and almost unknown in Javascript, I sought help from others to create a login code. The code was working fine earlier, but now it's not functioning as expected. Despite checking everything, I can&ap ...

Removing a CSS Class Using Tampermonkey: A Step-by-Step Guide

I'm completely new to CSS and javascript, so please bear with me. My goal is to remove the class disable-stream from each of the div elements located under the div with the class "stream-notifications". Below is an image for reference: Even though I ...

What is the process for incorporating a class into a table within TinyMCE using JavaScript?

I am facing an issue with adding a class to a table. I'd like the following code: <table></table> to transform into this code by clicking a button in tinymce. <table class="try-class"></table> I have added a button, bu ...

Exploring the issue: Why is data being submitted when cancelling an AngularJS and Bootstrap modal form?

Encountering an issue with AngularJS and Bootstrap UI in a modal Form where the form submission is triggered on cancel. Check out my Plunker for a demo of the problem. Upon cancellation, an Alert pops up during submission which should not occur. What am I ...

Tips for transferring information between two components when a button is clicked in Angular 2

I am currently working on a code that displays a table on the main page with two buttons, "Edit" and "Delete", for each row. When the Edit button is clicked, a modal opens up. My question is, how can I pass the "employee id" of a specific employee to the ...