Correctly define the vm function within the Controller As scope

I am a newcomer to javascript and AngularJS.

So... Maybe it's a simple question, but I've noticed two ways to define functions in javascript.

In the following controllers, pay attention to "grupoCancha" and "grupoVisible" (I included the entire script because there are other variables that need to be defined depending on the function).

Controller:

(function() {
'use strict';

angular
    .module('example.cancha')
    .controller('CanchaController', CanchaController);

CanchaController.$inject = ['$state', 'canchaService'];

function CanchaController($state, canchaService) {
    var vm = angular.extend(this, {
        canchasComplejo: [],
        grupoCancha: grupoCancha,
        grupoVisible: grupoVisible
        });


    (function activate() {
        loadCanchasComplejo();

    })();

    //function that calls the service to get the complex fields
    function loadCanchasComplejo() {
        canchaService.obtainComplexFields()
            .then(function(canchasComplejo) {
                vm.canchasComplejo = canchasComplejo;
            });
    }

    function grupoCancha(canchaComplejo){
        if (vm.grupoVisible(canchaComplejo)) {
            vm.grupoShown = null;
        } 
        else {
          vm.grupoShown = canchaComplejo;
        }
    }

    function grupoVisible(canchaComplejo){
       return vm.grupoShown === canchaComplejo;
    }


}
})();

The other way is a bit odd (maybe because of my background in Java). But the function definition is quite complex:

Controller 2:

(function() {
'use strict';

angular
    .module('example.cancha')
    .controller('CanchaController', CanchaController);

CanchaController.$inject = ['$state', 'canchaService'];

function CanchaController($state, canchaService) {
    var vm = angular.extend(this, {
        canchasComplejo: []
        });


    (function activate() {
        loadCanchasComplejo();

    })();

    //function that calls the service to get the complex fields
    function loadCanchasComplejo() {
        canchaService.obtainComplexFields()
            .then(function(canchasComplejo) {
                vm.canchasComplejo = canchasComplejo;
            });
    }

    vm.grupoCancha = function(canchaComplejo) {
        if (vm.grupoVisible(canchaComplejo)) {
            vm.grupoShown = null;
        } 
        else {
          vm.grupoShown = canchaComplejo;
        }
    };

    vm.grupoVisible = function(canchaComplejo) {
        return vm.grupoShown === canchaComplejo;
    };


}
})();

Could someone please explain which method is better for defining functions and why? Thank you!!

Answer №1

There are multiple approaches to writing Java Script, but it's best to adhere to the recommended usage outlined in the documentation. It's crucial to prioritize performance when dealing with large-scale applications. Opt for Minification to achieve optimal results.

I've made adjustments to your Controller 1, which now appears as follows:

(function() {
'use strict';
angular
    .module('example.cancha')
    .controller('CanchaController', 
                ['$state', 
                'canchaService',
                CanchaController]);

function CanchaController($state, canchaService) {
    var vm = this ;

        canchasComplejo: [],

        vm.grupoCancha=function (canchaComplejo){
                if (vm.grupoVisible(canchaComplejo)) {
                    vm.grupoMostrado = null;
                } 
                else {
                    vm.grupoMostrado = canchaComplejo;
                }
        }

        vm.cargarCanchasComplejo=function() {
                canchaService.obtenerCanchasComplejo()
                        .then(function(canchasComplejo) {
                        vm.canchasComplejo = canchasComplejo;
                        });
        }

        vm.grupoVisible=function(canchaComplejo){
                return vm.grupoMostrado === canchaComplejo;
        }
    }
}());

Upon minifying this code, it transforms into:

!function(){"use strict";function a(a,b){var c=this;c.grupoCancha=function(a){c.grupoVisible(a)?c.grupoMostrado=null:c.grupoMostrado=a},c.cargarCanchasComplejo=function(){b.obtenerCanchasComplejo().then(function(a){c.canchasComplejo=a})},c.grupoVisible=function(a){return c.grupoMostrado===a}}angular.module("example.cancha").controller("CanchaController",["$state","canchaService",a])}();

Considering this, I recommend following the guidelines presented in the Angular Style Guide by John Papa.

Hopefully, this guidance proves beneficial to you.

Maintain consistency in your approach and ensure unity within the team.

Wishing you success :).

Answer №2

One notable contrast I observe is the utilization of vm with the last two functions in the second snippet of your code. In the first example, you have:

function grupoVisible(canchaComplejo){
   return vm.grupoMostrado === canchaComplejo;
}

This function remains private within the scope of your controller's JavaScript code (given that your controller is immediately executed - (function(){})()) and cannot be accessed from the HTML directly. However, if you rewrite it as:

vm.grupoVisible = function(canchaComplejo) {
    return vm.grupoMostrado === canchaComplejo;
};

It becomes possible to access this function later on in the HTML using

ng-controller="CanchaController as cc"
, like so:

<div ng-controller="CanchaController as cc">
  <button ng-if="cc.grupoVisible()">SOME BUTTON</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

Is it not possible to call a function directly from the controller in AngularJS?

I have been trying to update a clock time displayed in an h1 element. My approach was to update the time by calling a function using setInterval, but I faced difficulties in making the call. Eventually, I discovered that using the apply method provided a s ...

Orchard's TinyMce now supports a drop event with jQuery integration

Currently in the process of constructing a website using Orchrad. I have implemented the tinymce4 html editor for building landing pages without any issues thus far. However, my current challenge involves capturing the jQuery drop event within the TinyMce ...

Looking to cycle through arrays containing objects using Vue

Within my array list, each group contains different objects. My goal is to iterate through each group and verify if any object in a list meets a specific condition. Although I attempted to achieve this, my current code falls short of iterating through eve ...

Incorporating S3 images into vanilla JavaScript within a Django storages environment

I am facing a simple issue that I cannot seem to resolve. I have configured Django storages to serve static files from S3. In my template, I define the image source like this: "{% static 'fun_share/img/logo/logo.svg' %}" with STATIC_UR ...

Having trouble appending a new attribute to the Mongoose output

In my Nodejs server application, I am working with a userDetail document that contains all the relevant user information. Additionally, I have a login document that stores the time of the first login, which I need to incorporate into the userDetails result ...

Mapping DOM elements to VueJS components for hydration is a key process in facilitating

I have a specific requirement and I am exploring potential solutions using VueJS, as it offers the convenient feature of hydrating pre-rendered HTML from the server. In my Vue components, I do not define a template within the .vue file, but I need them to ...

Basic PHP code converted into a JavaScript function for an onSubmit event within an HTML form

I have been trying to figure this out for hours. The goal is to submit a form only if one of the inputs matches a PHP echo. To simplify the script, it looks something like this: <head> </head> <body> <?php $A = rand(0,10); $B = r ...

Is there a method in AngularJS to compel TypeScript to generate functions instead of variables with IIFE during the compilation process with gulp-uglify?

My AngularJS controller looks like this: ArticleController.prototype = Object.create(BaseController.prototype); /* @ngInject */ function ArticleController (CommunicationService){ //Some code unrelated to the issue } I minified it using gulp: retur ...

Sketch the borders of the element (animated)

Seeking a way to create a button with an animated border that looks like it is being drawn. Current progress involves some code, but it's not working smoothly with border-radius set. (keep an eye on the corners) https://codepen.io/anon/pen/MbWagQ & ...

Automatically generated list items are failing to react to the active class

I am facing an issue with two divs in my project. The first div uses the Bootstrap class list-group and is populated with a basic example provided by Bootstrap. The second div is supposed to be populated with list-group-items obtained from an AJAX GET requ ...

Guide on smoothly transitioning between 2 points within a requestAnimationframe iteration

Would it be possible to acquire a library for this task, or does anyone have any suggestions for my psuedocode API? Inquiry: How can I create a function that accepts 4 parameters interpolate(start, end, time, ease) and smoothly transition between the sta ...

Using the AngularJS filter within the controller to only display values that are not empty

I'm facing a challenge with filtering a JSON object array to only include objects where a specific field has a value. The field I need to filter by can have any type of value, so I can't use a specific match condition. My goal is to implement t ...

Is Grouping Together Installed Private Modules Possible?

Exploring a modular JavaScript approach in my upcoming project is a new concept for me. I would prefer explanations to be simple due to my limited experience. I have uploaded my private package on npm: @name/package-name The private package contains mul ...

What is causing the click function to malfunction after selecting a second item?

I'm struggling to understand why my click function isn't functioning properly. You can view the JSFiddle here: http://jsfiddle.net/adbakke/ve9oewvh/ This is a condensed version of my HTML structure: <div class="projectDisplay"></div&g ...

Enabling or disabling a button dynamically in Ionic based on a conditional statement

I am looking to dynamically enable or disable buttons based on specific conditions. The data is retrieved from Firebase, and depending on the data, I will either enable or disable the button. For example, if a user passes the First Quiz, I want to enable ...

Leveraging AJAX for managing multiple selection options without the need for a submit button

Currently, I have a page featuring two select buttons. Whenever both are selected, the page should update automatically. Furthermore, each time a new option is chosen, the page needs to keep updating on its own. Below is my HTML code: <form action="" m ...

Wordpress team exhibition

Does anyone know how to create a Team showcase slider in Wordpress? I have been using slick slider, but I'm looking for a way to add team members easily through a plugin rather than manually. I found an image of what I want it to look like. Can any ...

Creating a curved edge for a shape in React Native can add a stylish and

Issue Description I am working on an app and struggling with styling the bottom navigation bar. It's more complex than what I've done before, especially the curved top edge of the white section and the area between the blue/green circle and the ...

Issue encountered when attempting to redirect following a jQuery Ajax request

I attempted to create a redirection mechanism upon receiving a successful response from the server. I followed instructions here, but unfortunately, I couldn't get it to work as intended. Below is the function responsible for sending data to the serv ...

Tips for showcasing an array in nested elements within an Angular mat-tree

I'm new to Angular and I need help displaying an array's values within the child elements of a material tree. Specifically, I want to show the names of fruits (such as Apple, Banana...) in the child elements. The colors and discounts from the ar ...