Different Techniques for Defining Functions in an AngularJS Controller Using the controllerAs Method

When using the 'controller as' approach instead of $scope, I am encountering issues with method calling from HTML. My question is, how many ways are there to declare and call functions using this approach?

First: (For executing something initially)

var vm = this;
vm.dataOne = [];

function funcOne() {
        myService.serviceFunc()
            .then(function(response) {
                vm.dataOne = response.data;
            });
    };
function activate() {
        funcOne();
        }
    activate();  

Second: (For initializing a variable based on a function's returned value)

 vm.dataTwo = function() {
        doSomething();
 }  
  • Are there any other ways?
  • How can we define a function in the controller that will be called from HTML, like

    ng-click="ctrl.dataTwo()";   
    

Answer №1

The way functions are defined in this context is considered private:

function functionOne() {

}; // This is the function body, no need for a semicolon

These types of functions are known as function declarations and are only accessible within the controller.

In order to call them, you need to assign them to the controller so they become controller variables:

vm.functionOne = functionOne;

An advantage of this method is that you can define functions after calling them, unlike with $scope or $this. These functions are recognized through hoisting and then called.

If you want to initialize a returned value from a function, simply call it like this:

vm.someVariable = someFunction();

For more information, check out these references:

var functionName = function() {} vs function functionName() {}

Private Members in JavaScript

Angular Function Declarations, Function Expressions, and Readable Code

Angular Style Guide

Answer №2

Implementing ng-controller="cntrl as vm" syntax:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
   angular.module('MyApp', [])
   .controller('MyCntrl', function($scope) {
       var vm = this;
       vm.name = 'Custom Directive';
   });
</script>
<body>

<div ng-app="MyApp" ng-controller="MyCntrl as vm">
  {{vm.name}}
</div>

</body>
</html>

Using controllerAs in a custom directive:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
   angular.module('MyApp', [])
   .directive('customDir', function() {
       return {
           restrict: 'EA',
           template: '<div>{{vm.name}}</div>',
           controller: function(){
               var vm = this;
               vm.name = 'Custom Directive';
           },
           controllerAs: 'vm'
       } 
   });
</script>
<body>

<div ng-app="MyApp">
  <div custom-dir></div>
</div>

</body>
</html>

Calling a function with "controller as" syntax:

<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script>
   angular.module('MyApp', [])
   .controller('MyCntrl', function($scope) {
       var vm = this;
       vm.name = 'Custom Directive';

       vm.someFunction = function() {
         vm.name = 'Button is Clicked!!!';
       };
   });
</script>
<body>

<div ng-app="MyApp" ng-controller="MyCntrl as vm">
 {{vm.name}}
 <input type='button' ng-click="vm.someFunction()" value="Click" /> 
</div>

</body>
</html>

Answer №3

Another approach is to utilize a function as constructor and enhance its capabilities using the prototype

function Controller($window) {
  this.$window = $window;
}

Controller.inject = ['$window']

Controller.prototype.click = function() {
  this.$window.alert('clicked')
}

angular.module('app', [])
.controller('controller', Controller)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='app' ng-controller='controller as ctrl'>
  <button ng-click='ctrl.click()'>Click me!</button>  
</div>

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

Choose a radio button from a React Native FlatList

I am new to React Native and I'm working with the expo-radio-button component. However, I'm facing an issue where I can't seem to select only one radio button at a time in a flatlist. When I try to select a single button, it ends up select ...

Adjust the CSS of a nested div within the currently selected div upon page load

I am facing an issue with a page that users access by clicking through an ebook. Upon clicking a link, they are directed to a specific product on the page, and the URLs look like example.com/#product1 example.com/#product6 example.com/#product15, etc... ...

The webpage containing the authRequired meta briefly flashes on the screen, even if there are no active login sessions on Firebase

As a beginner in Vue and web development, I have been enjoying my journey so far but now I find myself stuck. Currently, I am working on creating an admin dashboard with Firebase authentication. Everything seems to be functioning as expected, except for on ...

Having issues with clicking on a row in the table while using AJAX functionality

Experiencing a puzzling issue while attempting to add click functionality to table rows with AJAX, here is the JavaScript code used: //for tabs $(document).ready(function () { $("#tabs").tabs(); }); $(window).load(function() { jsf.ajax.addOnEven ...

Looking for a way to make this HTML tab appear using ng-show and an external variable in AngularJS - seeking guidance as a beginner!

Here is the HTML code snippet controlling the tab presentation: <li class="presentation" ng-show="currentUserAuthority == LIBRARIAN" > However, there seems to be an issue with the variable "currentUserAuthority" not updating until after the web pag ...

Next.js appending [object%20Object] to the URL's endpoint

I encountered an error when launching my next app using "npm run dev". The error occurred during the pre-render attempt: GET http://localhost:3000/aave/fundamentals/economics/[object Object] [HTTP/1.1 404 Not Found 434ms] The issue is not specific to thi ...

Request Timeout: The server took too long to respond and the request timed out. Please try again later

I'm encountering an issue when attempting to send a dictionary as a JSON to the express API. The error message I keep receiving is: Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_NSURLErrorFailingURLSessionTaskErrorKe ...

How to detect internet connection in any screen using React Native?

I'm facing confusion regarding how to display my customDialog when there is no Internet connection in my app. Currently, I have successfully shown my customDialog only in the LoginScreen. However, I want to display it from different screens, not just ...

What is the best way to ensure that circles only touch each other by their edges?

Trying to align three circles touching each other has been a challenge for me. Although I have successfully managed to make two touch, the third one remains elusive. How can I ensure that all three circles are in contact with each other, especially when th ...

What are the key distinctions between an arrow function, a class, and a traditional function?

Is there a way to distinguish between the following three elements in ES6 using its reference? let x = i => i+1; class y { constructor(i) { this._i=i+1; } get i(){ return this._i;} } function z(i) { return i+1; } For example: test(x) //=> ' ...

Dynamic connections with Meteor and AngularJS

My publication relies on a specific parameter from the client, so when subscribing from the client side, I need to send this parameter to the server. I am utilizing the angular-meteor package and have come across the $subscribe wrapper. The syntax for usag ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

What are the distinctions between manually and programmatically changing URLs in Angular 6?

My query pertains to differentiating navigation methods, specifically between clicking a button with [routerLink] and manually entering a URL in the browser's search bar. Update: I have a fixed menu on a certain page that appears as follows: <ul& ...

Having trouble with shipit.js deployment: Error encountered - git checkout undefined

I have been using shipit.js to deploy my nodejs application on an Ubuntu 16.04 server successfully. However, I recently encountered the following error: ./node_modules/shipit-cli/bin/shipit production deploy start Running 'deploy:init' task... ...

The sequence for conducting operations within a function in JavaScript (Vue.js)

I am currently working on building a contact-list app using Vue.js. Each contact in the list can have multiple addresses, emails, and phone numbers. To accommodate this, I have set up inputs and a button to add additional fields as needed. My issue arises ...

Choose options with selectize.js including option separators

My list of countries includes options with dashes as separators, but when I use selectize they disappear. How can I visually separate items in the list without using labelled option groups? <select class="form-control" id="Country" name="Country"> ...

Create a dropdown menu using a PDO query to populate the selectable options

I need to create a Select List that dynamically populates items/information from a Query. I understand the importance of updating the select list every time the database is updated, so JQuery is required for this task. Although I have limited experience wi ...

Utilizing the jQuery slideToggle method on the specified target element

I'm encountering an issue with jQuery slideToggle, and here's the code I have: $(".dropdownmainmenu").click(function(){ $(this).children(".showmenu").slideToggle(); $(this).toggleClass("activemainmenu"); $(this).find(".showarrowmainmen ...

Eliminate all the zeros from the date string

Trying to work with a string that is in the format '01/02/2016' and my goal is to eliminate the leading zeros so I end up with '1/2/2016' using regex. So far, I have attempted '01/02/2016'.replace(/^0|[^\/]0./, '&ap ...

What is the reason for ng-submit not being prevented by a mandatory select field?

In an HTML5 form, when a select element is required and no option is selected, the appropriate styling for invalidation is applied. However, the ng-submit still allows the form to be submitted. Why does this occur and is there a way to prevent submission ...