AngularJS: incorporating various functionalities within a single controller

I have a basic AngularJS controller that I am working on, and I would like it to include two separate functions:

var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http, $log) {
    //Function 1
    $scope.search = function() {
        $http.post('server.php', { "data" : $scope.keywords})
        .success(function(data, status) {
            $scope.result = data;
        })
    };

    //Function 2
    $scope.tableClick = function() {
          $log.log('Hello World!');
    };

})

I seem to be encountering a syntax issue because the script only works when I remove the second function.

When I try running the script with both functions included (as shown above), I am seeing {{ x }} for the content of the following HTML elements:

<tr ng-repeat="x in result">
<td><a href="www.test.com" >{{ x }}</a></td>

Any ideas on what could be causing this?

Answer №1

As mentioned previously, there is no equivalent to echo 'Hello World!' in JavaScript. To display the phrase on the DOM, you must use it as a simple expression like this:

$scope.helloWorld = 'Hello World!';

Then, in the HTML, you can call it with {{helloWorld}}. It seems like you are trying to test it with a function. In that case, make sure to return the string 'Hello World!' as shown below:

$scope.helloWorld = function () {
    return 'Hello World';
};

In the HTML:

{{ helloWorld() }}

If you simply want to "log" the Hello World! to the console (assuming you are not overlooking JS errors): AVOID USING console.log();. Instead, utilize AngularJS' built-in service $log.

A more improved code

However, if I were in your shoes, I would approach the code differently. Here's an example:

var app = angular.module('searchApp', []);
app.controller('searchCtrl', function ($scope, $http, $log) {
    //1st function
    $scope.search = function () {
        $http.post('server.php', { "data" : $scope.keywords })
        .then(function (resp) { //use then instead of success/error
            return resp.data;
        }, function inCaseOfErrors (err) { //named just for teaching purposes
            $log.log(err);
        });
    };

    //2nd function
    $scope.tableClick = function () {
        $log.log('Hello World!');
    };
})

Answer №2

Ensure that the values in your $scope.result are correct. Keep in mind that there is no echo function in JavaScript.

In the code snippet below, I have removed the server call and used hardcoded data for testing purposes:

var app = angular.module('searchApp', []);
app.controller('searchCtrl', function($scope, $http) {
    $scope.result = ["apple", "orange", "raisin", "banana"];
    
    $scope.search = function() {
        // Simulating server response
    };

    $scope.tableClick = function(item) {
        console.log("Someone clicked on the table! Row: " + item);
    };
})

HTML:

<table>
    <tr ng-repeat="item in result">
       <td data-ng-click="tableClick(item)">{{ item }}</td>
    </tr>
</table>

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

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...

The dynamic page fails to export with a static export in NextJS, resulting in an output error: "

I'm struggling to export a route in my NextJS 14 project. I've set the output to export and all routes are exporting correctly except for the dynamic ones. The folder for the dynamic route is not showing up in the output folder The version of Ne ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

What is the method to retrieve the selected value from a drop-down menu that is connected to JSON keys?

I am just starting to learn AngularJS and I need help with binding column names (keys from key-value pairs) to a select list. I want to be able to retrieve the key name when the selection in the select list is changed. The select list displays: name, snip ...

Different ways to save data fetched from a fetch request

I'm fairly new to React and could use some assistance. I am trying to retrieve data from a movie database based on a search term. I have a method called getMovies where I utilize fetch to grab the data. The information is located in data.Search, but I ...

Error arising from attempting to compile React animations for a specific component, rc

As someone new to React, I decided to try running a sample example from the following link: To do this, I created a file named MonApp.js with the code snippet below: import React, { Component } from 'react'; import { render } from "react-dom"; ...

Tips for persisting objects created in PHP while utilizing XMLHttpRequest

Currently, I am working on a web page with the index.php file structured as shown below: include('UserClass.php'); include('html/top.php'); $user = new User(); if (isset($_POST['user'], $_POST['pass'])) { $user-& ...

Internet Explorer's support for the `<summary>` tag in HTML

Is there a method to enable the summary tag in Internet Explorer 11, such as using an external library? <details> <summary>Here is the summary.</summary> <p>Lorem ipsum dolor sit amet</p> </details> App ...

Ways to conceal a child div element without using any specific ID reference

I encountered an issue where I need to conceal all divs within a parent div except the first one. The challenge is that these divs do not possess any unique identifiers. Is there a way to achieve this task using CSS or pure JavaScript? <div role="list ...

Is it possible to configure the async.retry method to retry even upon successful queries, depending on a specific condition?

Currently, I am delving into the node.js async module and wondering if it's possible to modify the behavior of the async.retry method. Specifically, I'd like it to retry even on successful operations but halt based on a certain condition or respo ...

Guide to activating animation on one element when hovering over another element?

I am setting up an HTML 5 range element and looking to enhance the user experience. Specifically, I want to implement a feature where when the user hovers over the range, the height and width of the thumb should increase to 12 pixels. CSS .myrange::-webk ...

In Javascript, a function is executed only once within another function that is set on an interval

Using the Selenium Chrome driver in my JavaScript, I am constantly checking a value on a website every 2 seconds. However, I need to only save status changes to a text file, not every single check. The current code is functional but it saves the text fil ...

Why is Puppeteer failing to download to the designated folder using "Page.setDownloadBehavior" in Windows?

When trying to download a file using Puppeteer, I found that the code works perfectly on a Mac OS machine but fails on a Windows machine. The code snippet I used is shown below: await page._client.send( 'Page.setDownloadBehavior', { beha ...

Creating atomic controller actions in Sails.js: A guide to optimizing your controller functions

If I am looking to perform multiple operations within a Sails.js controller, how can I ensure that these actions are atomic to maintain the correctness of the results? This includes not only database operations but also various Javascript processing tasks. ...

Combining inheritance and isolated scopes: a comprehensive guide

I've encountered a situation where I need to sort an HTML table. Here is the code snippet: <table> <thead> <tr> <th custom-sort-one order="'Name'" >Name</th> </ ...

Is there a way to assign a role to a user without requiring them to send a message beforehand?

I've been searching for a solution to this issue, but all I could find were instructions on how to assign a server role to someone who has interacted in some way. Is there a way to locate a specific user on a server and assign a role to them without ...

Can the AJAX URL be loaded onto a new page?

https://i.stack.imgur.com/5l63v.pngPardon the poorly phrased question, but I need some guidance on a specific requirement regarding opening a URL in a new page. Currently, I have designed an AJAX URL and I'm wondering if it's possible to open thi ...

Switch the div class when clicked, and revert it when the body is clicked

Allow me to elaborate on the issue: I currently have <div class="contact"> <div id="form"></div> <div id="icon"></div> </div> My goal is to change the class of .contact to .contactexpand (or simply ...

Unable to create module instance, despite correct module definition

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="../angular/angular-1.6.7/angular.js"/> <script src="../angular/angular-1.6.7/angular-route.min.js"/> <!--script type="text/ja ...