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

Leveraging a static value in a service within AngularJS

I'm encountering an issue where two constants used within a service are showing up as undefined. Strangely, I have also included these constants in different controllers without any problems with undefined variables. Why is this happening? var app = ...

What is preventing me from extracting the callback function from the app.get method in Node.js and Express?

In my server.js file, I'm attempting to do the following: // This code is not functioning as expected, and I am unsure why. var findBooks = function (err, books) { if (!err) { return response.send(books); } else { console.log( ...

Rotate Text in HTML <thead> Tag

I need assistance with rotating a table header. https://i.stack.imgur.com/hcvxx.png The HTML th elements within the thead section are described as follows: <th> <span class="rotate-all">Period</span> </th> <th> < ...

Validate that a string is a correct file name and path in Angular without using regular expressions

Currently, I am using regex to determine if a string is a valid file name and path. However, when the string length becomes longer, it ends up consuming a significant amount of CPU, resulting in browser performance issues. public static readonly INVALID_F ...

Discord between Bootstrap tabs and C3 charts: A Compatibility Str

On my website, I have implemented Bootstrap navigation tabs that each contain a chart. The issue I am facing is that when I navigate to the home page, the chart in the active tab displays perfectly fine. However, for the other tabs, the charts overlap with ...

Using React.js to add MongoDB documents into the database

Is there a way to directly insert documents into a MongoDB collection from a React component? I have been working on a personal project, which is a chat web application used for training purposes. For instance, when a user wants to post a new message in a ...

Update the image source every few seconds

I am attempting to show the same image in both gif (animated) and jpeg formats. I am updating the src every few seconds. After checking in the developer tools, it seems that the src has been modified, but the gif does not appear to be animating. setInter ...

Choosing Text with JavaScript

I am looking to enhance the appearance of text on an HTML page by making it bold. I have implemented the following code: <script type="text/javascript" > function getSelectedText(){ if(window.getSelection){ ; return window.getSelect ...

When programming with PHP and JavaScript, managing events' start dates and end dates

In my current project, I am developing a script that deals with events. An event is scheduled to start on 12/02/2016 at 11:20 and end on 01/04/2016 at 8:20. When the end date is reached, I need to trigger a specific action using JavaScript. if (t.getFullY ...

Retrieve information from individual XML nodes in a parsed string

When making an Ajax call to retrieve XML data from a different domain using a PHP proxy to bypass cross-origin restrictions, I am unable to extract the values from the XML nodes and display them in my HTML tags. Despite no errors showing up in the browser ...

React - 'classProperties' is not currently activated in this setting

Recently, I incorporated Truncate-react into my project. Subsequently, React prompted me to install @babel/plugin-proposal-class-properties, which I promptly added to the package.json file as follows: "babel": { "presets": ...

Unit testing Vue 3 by simulating the push() method of vue-router

As a newcomer to Vue and StackOverflow, I wanted to share my issue. While attempting to run the unit test for my application, I encountered a TypeError. The error message stated: "TypeError: Cannot read properties of undefined (reading 'push')" ...

Adaptive Images with jQuery Mobile Listview

I have been experimenting with the classic listview example featuring thumbnails from the jquery mobile documentation. However, when I upload images of different sizes, they do not display properly due to resolution issues. How can this be resolved? Here ...

Streamline repetitive scope attributes in AngularJS

After noticing that I was using a repetitive structure, I want to simplify it: <container> <clock property="data"></clock> <calendar property="data"></calendar> <alert property="data"></alert> </container ...

Next.js Error: The text displayed on the page differs from the HTML rendered by the server

Currently, I am facing an issue with the error "Error: Text content does not match server-rendered HTML." Here is my scenario - I have received a dateTime from an API, for example '2022-12-25T11:22:37.000Z', and I want to display it on a compone ...

Attempting to remove the current click event listener and add a new event listener

I am attempting to remove the click event binding and replace it with another click event after the button has been clicked once. <small id="selectall_agriculture" onclick="refineSearch.testing('agriculture')">(select all)</small> O ...

Is using an underscore in a directive's name allowed in AngularJS?

I've encountered an issue with angular directive naming conventions and how Angular normalizes directive names. To adhere to specific naming conventions within an existing project that I am integrating Angular into, I need to name my custom directiv ...

How can I update the color of a list item when it is clicked within a foreach loop using knockout js?

Currently, I am encountering an issue with changing the color when a user clicks on a list item using the latest version of knockout js. My goal is to change the color of a list item when it is clicked and maintain that color until another item is clicked, ...

Generating prime numbers in Javascript

My attempt at generating the prime numbers less than 20 using my current knowledge is as follows: let arr = []; for (let x = 3; x <= 20; x++) { for (let i = 20; i > 0; i--) { if (x % i !== i) { arr.push(x) } } console.log(arr) ...

Is there a benefit to using middlewares instead of the standard built-in functions in Express.js?

Express.js offers a wide range of middlewares that replace built-in functions. One example is body-parser, which parses HTTP request bodies, replacing the built-in function express.bodyParser. body-parser replaces the built-in function express.bodyParse ...