Leveraging $http in Angular without the need for $scope

When using the syntax

<div ng-controller="BuildingsCtrl as bc">
to avoid using $scope (as mentioned here), how should I incorporate $http?

In other words, how can I refactor the following code without relying on $scope?

angular.module('atlasAngularApp')
    .controller('BuildingsCtrl', function ($scope, $http) {
        this.awesomeThings = [
            'HTML5 Boilerplate',
            'AngularJS',
            'Karma'
        ];
        this.getBuildings = function () {
            $http.get('http://localhost:40602/api/1.0/buildings')
                .then(function successCallback(response) {
             ======>    $scope.buildings = response.data;
                    }, function errorCallback(response) {
                        alert("Error");
                }
            );
       }
   });

To expand on this,

<li ng-repeat="thing in bc.awesomeThings">
    {{ thing }}
</li>

Using this.awesomeThings functions properly, allowing a view to utilize this, but the following does not work:

angular.module('atlasAngularApp')
    .controller('BuildingsCtrl', function ($http) {
        var self = this;
        this.getBuildings = function () {
            $http.get('http://localhost:40602/api/1.0/buildings')
                .then(function successCallback(response) {
             ======>    self.buildings = response.data;
                    }, function errorCallback(response) {
                        alert("Error");
                }
            );
       }
   });

(note the self.buildings part.)

I've experimented with various versions of this approach, but have yet to find a solution that works. This question is relevant, though my attempts to adapt it to my code have been unsuccessful.

It's worth mentioning that I don't have anything against $scope; I'm simply trying to adhere to the Angular conventions endorsed by Yeoman-generated projects. Additionally, I'd appreciate an explanation of why $scope may be viewed negatively.

As a reference, here is my view. Is there possibly an issue within it?

<div ng-controller="BuildingsCtrl as bc">
    <table ng-init="buildings = bc.getBuildings()">
        <tr ng-repeat="building in buildings">
            <td>{{ building.name }}</td>
            <td>{{ building.code }}</td>
            <td>{{ building.image }}</td>
        </tr>
    </table>
</div>

The code functions correctly when employing $scope.

Answer №1

When you use

ng-init="buildings = bc.getBuildings()"
, make sure you are returning a value to bind to the variable buildings. Instead of assigning values to self.buildings, which indirectly refers to this.buildings, ensure that you assign to this.buildings directly, so that bc.buildings is what is referenced in your view.

<tr ng-repeat="building in bc.buildings">

This will properly repeat your elements.

Regarding the use of $scope and this, for a detailed explanation, refer to this post: 'this' vs $scope in AngularJS controllers

Answer №2

At the outset, it's important to note that calls to a backend should not be directly made by the controller. Instead, create a service to handle this task.

Typically, controllers are structured like this:

angular.module('atlasAngularApp')
.controller('BuildingsCtrl', function ($scope, $http) {
    var vm = this;
    vm.awesomeThings = [
        'HTML5 Boilerplate',
        'AngularJS',
        'Karma'
    ];

    vm.getBuildings = getBuildings;



    function getBuildings() {
        $http.get('http://localhost:40602/api/1.0/buildings')
            .then(function successCallaback(response) {
                vm.buildings = response.data;
                }, function errorCallback(response) {
                    alert("Error");
            }
        );
   }
});

This allows you to iterate over the buildings stored in vm within your HTML:

<li ng-repeat="building in bc.buildings">
   {{ building }}
</li>

A valuable reference for best practices is John Papa's styleguide: https://github.com/johnpapa/angular-styleguide

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

A tutorial on creating circular patterns within a pyramid structure using p5.js and matter.js

I've been attempting to create a pyramid shape using multiple circles, similar to this: balls in pyramid shape To achieve this, I've developed a 'Balls' class: class Balls { constructor(x, y, radius, color, ballCount) { this.x = ...

Updating AngularJS to have the same page TITLE tag as the page's H1 tag

Is there a way to dynamically update the title tag of my page based on the H1 tag in AngularJS? In jQuery, I could achieve this by: var title = $('#content').find('h1').first().text(); if (title.length >= 1) { document.title = ...

In Javascript, navigate to a specific section by scrolling down

Currently, I am in the process of enhancing my portfolio website. My goal is to incorporate a CSS class once the user scrolls to a specific section on the page. (I plan to achieve this using a JavaScript event). One approach I am considering is initially ...

The ajaxStart() and ajaxStop() methods are not being triggered

I'm currently working on a Q/A platform where users can click on specific questions to be redirected to a page dedicated for answers. However, when a user tries to answer a question by clicking the "Answer" link, certain background processes such as ...

The background-size:cover property fails to function properly on iPhone models 4 and 5

I have taken on the task of educating my younger sister about programming, and we collaborated on creating this project together. Nicki Minaj Website However, we encountered an issue where the background image does not fully cover the screen when using b ...

Skipping validation while navigating back on SmartWizardIf you need to bypass validation during backward

Looking for assistance with Jquery smartwizard? Check out the link. I want to disable validation when a user clicks on the "Previous" button in any step, except for the first step where the Previous button is disabled by default. Below is my JavaScript co ...

PHP loop causing malfunction in jQuery Tooltip feature

I am trying to enhance my website with tool-tips, and I found this useful code snippet at In order to create table rows <tr>, I have implemented a while loop. The structure of my tool-tip <div> is as follows: <td class="maandgem">&e ...

Tips for establishing a connection to a proxy server and executing an http.request through the proxy using nodejs

I'm looking to establish a connection to a proxy in order to send http requests through it. For instance: proxy.connect(someip:someport,function(){ console.log('[PM]['+this._account+'] Logging in..'); var auth_re = /auth& ...

Determine the full location information with the help of Google Maps SDK without the need

My current challenge involves dealing with a list of unformatted and incorrectly written addresses. I am seeking a way to iterate through these flawed strings and generate more organized and accurate addresses using one of the many Google Maps SDKs availa ...

Steps for adjusting the position of this div in relation to the main container

Apologies in advance for my lack of HTML skills. I am struggling with a page layout issue. I have a website at . When the window is resized, the ads div on the right side overlaps the main container. What I would like to achieve is to make this ads div re ...

Express-hbs: Dynamic Helper Function with Additional Features

I am currently utilizing express-hbs and Async Helpers in my project. However, I am facing an issue with passing options to the helper as async helpers do not seem to support this feature (or maybe I am unaware of how to do it correctly). In the code snipp ...

Utilizing JavaScript to Parse RSS XML Feeds Across Domains

Looking to parse an RSS (XML) file without relying on the Google RSS feed. I have attempted using JSONP, but it resulted in downloading the file and throwing an error "Uncaught SyntaxError: Unexpected token < ". $.ajax({ type: "GET", ur ...

How to Ensure Screen Opens in Landscape Mode with Phaser3

https://i.stack.imgur.com/keCil.pngIn my Phaser3 game, I am trying to achieve the functionality where the game opens horizontally in a webview without requiring the user to rotate their phone. The vertical photo below shows the game in its current state. W ...

Angular2: The comeback of accessing a getter after the service constructor has completed (using HTTP Get)

I have a requirement for my app where I need to utilize List.json to create a list, which forms the core of my application. To ensure this list is shared across all components, I have opted to establish a service. Within this service, I call my JSON file ...

Can images be placed on the border?

Hi there! I am trying to add an image on a border with a 100px solid width using CSS. I have experimented with positions and z-index, but I can't seem to get the desired effect. Any ideas on how to achieve this? Here is an example image: https://i.sst ...

perform an action in PHP when a button is clicked

I'm currently developing a PHP admin panel that displays a list of users in an HTML table format. Each row in the table includes a button that allows the admin to send a notification to the selected user. Below is the code I used to create and displa ...

Facing difficulties in resetting the time for a countdown in React

I've implemented the react-countdown library to create a timer, but I'm facing an issue with resetting the timer once it reaches zero. The timer should restart again and continue running. Take a look at my code: export default function App() { ...

Issues encountered with AngularJS directive binding inner content not functioning as expected

I am currently developing a feature toggle directive, which requires a check to be performed in order to display content if the check is successful. I want the directive to replace itself with its content without creating a new child scope (so I'm try ...

What is the best way to retrieve a specific key from a JavaScript Map containing an array?

I am currently iterating through a two-dimensional array to populate a map. The map is using the [i,j] indices as keys and the corresponding arr[i][j] values as values: const arrMap = new Map() for(let i = 0; i < arr.length; i++){ for(let j = 0 ...

Creating a dropdown menu in Bootstrap 5 without using any of the Bootstrap

In my Angular application, I have a header with icons and pictures that I would like to use as dropdown menus. The code snippet for this functionality is shown below: <li class="nav-item dropdown"> <a class="nav-li ...