Enhancing AngularJs code effectiveness through the use of MVC framework

I'm completely new to AngularJs and still trying to grasp the concepts. I have a few questions that I hope someone can help me with:

  1. Is it possible to trigger code in the controller only when a button is clicked, rather than having it load with the view?
  2. Or does the controller always load with the view, making it impossible to isolate certain functions to onclick events?
  3. What is the best way for me to create a function that will only execute when a button is clicked, and not every time the page loads? (In an AngularJs manner)

This is the HTML section:

<ion-view view-title="Account Fixer">
      <ion-content class="padding">
        <div class="list">
            <label class="item item-input item-stacked-label">
                <span class="input-label">IrId</span>
                <input type="text" placeholder="irid" value="{{irid}}" disabled>
            </label>
            <label class="item item-input item-stacked-label">
                <span class="input-label">Email</span>
                <input type="text" placeholder="Enter New Email" value="{{email}}">
            </label>
            <button class="item button button-block button-positive" ng-click="postForm()">Fix Issue</button>
        </div>
      </ion-content>
    </ion-view>

And this is my controller:

.controller('TestCtrl',function(Test,$scope, $http, $stateParams){

$scope.email = Test.get('AB12345').email;
$scope.irid = Test.get('AB12345').irid;

//I want this to be triggered only on onclick
    $scope.postForm = function(dataForm){

    var encodedString = 'action=' + 
            encodeURIComponent("QA_fixEmail") +
            '&irid=' +
            encodeURIComponent(Acct.acctData().irid) + 
            '&email=' +
            encodeURIComponent(dataForm.email) + 
            '&password=' +
            encodeURIComponent("abcd1234");
    $http({
        method: 'POST',
        url: 'someservice',
        data: encodedString,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    .success(function(data,status){
        console.log(status);
    })
    .error(function(data, status){
        console.log(status);
    })
}
})

Answer №1

Q: Can you trigger a function... in onclick events only?

A: Absolutely! Simply utilize ngClick

Check out these examples:

AngularJS Events

Keep in mind that one link uses ng-click, while the other link uses ngClick. They are interchangeable:

AngularJS, ng-click vs ng:click vs ngClick

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

Steps to automatically launch a URL upon button click and executing PHP script

I have a Joomla website and I am facing a challenge in automatically triggering a modal window that displays a web page based on parameters passed through the URL. The scenario on my website is as follows: A trip leader selects a trip and schedules it by ...

Boolean Filtering in Angular and Ionic

Can someone help me understand why I'm not getting a boolean value from this code snippet?: var category_data = $filter('filter')(data, {id: id}, true)[0]['subs']; Instead of returning true or false, it seems to be giving me some ...

Are there any available npm modules for accurately tallying the total word count within a document saved in the .doc or .doc

I Need to tally the number of words in doc/docx files stored on a server using express.js. Can anyone recommend a good package for this task? ...

Angular CDKScrollable not triggering events

I'm having trouble making the angular CdkScrollable work when creating my own div: <div class="main-section" id="mainsection" #mainsection CdkScrollable> <div class="content" style="height: 300px; backgr ...

The module named 'MyApp' cannot be found or accessed

I've incorporated Angular into my MVC project. After adding the following js file and naming it MyApp.js (function () { //Creating a Module var MyApp = angular.module('MyApp', ['ngRoute']); // Will use ['ng-Route'] w ...

How to apply unique styles to multiple elements with the same class using jQuery?

How can I add different classes to multiple div elements with the same class based on their content? <div class = "flag"> Yes </div> <div class = "flag"> No </div> <div class = "flag"> Yes </div> <div class = "flag"& ...

How can an object inside an array be destructured in just one line?

Consider the following array: const array = [{b:2}] Can you extract the value of b using destructuring in just one line? I attempted something similar to this approach, but it did not yield the desired result: const [{b} = array] ...

Is there a way to remove the bold styling from text next to JavaScript?

I recently launched a website at www.mvscaccounting.com, and I added a search engine made from javascript at the bottom of the page. Next to it, I wanted to put a "all rights reserved" notice. However, whenever I try to add any text next to the search engi ...

What sets apart elem['textContent'] from elem.textContent?

When dealing with a HTMLElement in JavaScript, is there any distinction between the following lines of code: elem['textContent'] = "Test"; versus elem.textContent = "Test"; This question arises when setting the text content of an HTMLElement. ...

What is the method for altering the state of a single element within a map?

As I delve into learning React, I encountered a persistent issue that has been absorbing my time for several hours now. The problem revolves around mapping an array of product sizes to buttons and controlling the state change of only the last clicked butto ...

Incorporating the angular UI router effectively by reusing the same templateUrl and controller multiple times

Exploring the AngularUI Router framework for the first time, I am curious about how to enhance the code snippet below. Everything is functioning well at the moment, but as the project progresses, it will feature 20 questions or more. I want to avoid repea ...

"Troubleshooting issues with data loading using React's useEffect function

While working on my project, I encountered a strange issue where the isLoading state is being set to false before the data fetching process is completed. I am using the useEffect hook to show a loading spinner while fetching data from an API, and then disp ...

Updating a behavior object array in Angular 5 by appending data to the end

After creating a service to share data across my entire application, I'm wondering if it's possible to append new data to an array within the userDataSource. Here is how the service looks: user.service userDataSource = BehaviorSubject<Array& ...

Error encountered in MEAN stack due to Angular - Unhandled Error: $injector:modulerr

I am encountering an issue while working on a MEAN stack project. Everything seems to be going smoothly initially, but as soon as I add a few more lines of code in Angular, an error pops up. Despite following various online courses on MEAN stack developmen ...

Retrieving the IPv4 Address from an Express.js Request

I am currently working on setting up a whitelist for IP addresses in my API. However, when I use request.socket.remoteAddress in Express.js, I receive an IPv6 address (I believe) that looks like this: ::ffff:127.0.0.1. My main concern is how can I extract ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Utilizing hyperlinks within NicEdit content and managing events with jQuery

I am using nicEdit, a rich editor, on my website to insert hyperlinks into the content. While I can successfully add hyperlinks using the setContent() method after initializing nicEdit, I am facing issues with handling click events for hyperlinks that have ...

The VueJS Hello world application is experiencing technical difficulties and is currently not functioning as

As a complete VueJS newbie, I've just started working on my very first app. It's supposed to be a simple Hello World application, but unfortunately, the code isn't quite behaving as expected :( HTML <!DOCTYPE html> <html lang=" ...

Guide: How to include a date value within a JSON format? [See code snippet below]

Currently, I am developing a react application that includes a form with sections for basic details and employment information. The form is almost completed, and I have successfully structured the data in JSON format for different sections. To see a work ...

Navigating a collection of objects after a button is clicked

My current library project involves looping through an array of objects to display them on a grid based on input values. Here is the code snippet for my loop: const addBook = (ev) => { ev.preventDefault(); let myLibrary = []; let bookIn ...