The inconsistency between updating data in the model and its corresponding binding in the controller

I've been attempting to implement this specific approach in my application, but I'm encountering difficulties.

CountriesModel.js

app.service('CountriesModel', ['$http', 
function($http) {
    $http.get(baseUrl + 'api/countries').success(function(data) {
        this.countries = data;
    });
}]);

UserCtrl.js

app.controller('UserCtrl', ['$scope', 'CountriesModel',
    function($scope, CountriesModel) {
        $scope.CountriesModel = CountriesModel;
}]);

user.html

<select ng-options="country.iso2 as country.short_name for country in CountriesModel.countries" ng-model="selectedCountry"></select>

Despite seeing that countries inside CountriesModel are retrieved properly in the AngularJs inspector plugin, I'm still encountering an issue where $scope.CountriesModel inside UserCtrl remains undefined and the select element remains empty...

Answer №1

After hours of frustration, I finally cracked the code. It turned out to be more of a JavaScript closure issue than an AngularJs problem.

Here's the solution that worked for me:

app.service('CountriesModel', ['$http', 
function($http) {
    $http.get(baseUrl + 'api/countries').success(function(data) {
        this.countries = data;
    }.bind(this));
}]);

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

The background image is not appearing on the div as expected

I've been attempting to create a div and set a background image for it using jQuery, but I seem to be facing issues. When I try setting the background color to white, it works fine. Here's the code snippet: function appendToDom(poster) { ...

If you refer to a function, are you personally calling the function or asking the reference to call it?

From what I understand, and please correct me if I'm mistaken, when a variable is assigned to a function in the form of a function expression, it doesn't hold the function in the same way that it holds a primitive value. The variable simply refer ...

Is there a specific directive in Angular that allows for variable declarations using the "

This interesting piece discusses the usage of a let-name directive in the template: <ng-template #testTemplate let-name> <div>User {{ name }} </div> </ng-template> Can anyone tell me if this is a part of the standard ang ...

Altering CSS attribute values using a random number generator

Is there a way to randomly change the animation-duration attribute in the following CSS code? I want it to range from 0 to 1. @keyframes blink { 50% { border-color: #ff0000; } } p{ animation-name: blink ; animation-duration: 0.1s ; animatio ...

A solution for accessing computed properties within a v-for loop

Currently, I am facing a challenge with the code provided below. It seems that computed properties do not support parameters. Do you happen to have any suggestions on how to overcome this issue? I am considering using watchers on functions but I am also ...

Converting a variable with a cloned object from jQuery to vanilla JavaScript

const clonedBoardCode = $('#board_code').contents().clone(false); alert( clonedBoardCode.filter('div').eq(x).children().eq(y).text() );//need to fix this I am looking for a code similar to this $('#board_code_dup > div') ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...

Is there a way to configure $urlRouterProvider.otherwise to redirect to a specific state rather than a path?

I'm trying to navigate to a state instead of just a path, but I'm struggling to find the right solution. ...

Submitting a form automatically in React Native using Redux

Is there a way to automatically submit a Redux Form in React Native based on certain conditions being met? I attempted to do so below, but it resulted in a warning. The documentation provides an example for remote submitting, but it uses HTML form's ...

What is the best way to set the width of a w2grid to 100%

Has anyone tried using w2grid before? I'm having trouble figuring out how to make it fill its container 100%. Here's the HTML snippet: <div id="a" style="width:100%"> <!-- top left container--> <div>This ...

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

Having trouble accessing the $scope property value in AngularJS

1. script.js var appProfileInfo = angular.module('profileInfoApp', ['ngMaterial','ngAria','ngAnimate','ngRoute' ]); 2. messageController.js appProfileInfo.controller('messageController', functi ...

How can I modify the mesh structure in Three.js?

Having two meshes, mesh1 and mesh2, each with the same number of vertices and extrusion. mesh1 = 5000 vertices. mesh2 = 5000 vertices. I transfer the vertices from mesh2 to mesh1. Then I execute: mesh2.geometry.verticesNeedUpdate = true; mesh2.geometry. ...

Executing multiple functions with onPress in React Native

When I press onPress using TouchableOpacity, I am attempting to invoke multiple functions. Here's an example: functionOne(){ // perform an action } functionTwo(){ // execute something } <TouchableHighlight onPress{() => this.functionOne()}/& ...

Whenever I try to relocate my HTML file that references three.js, the three.js library seems to malfunction and stop

Something strange is happening... I recently downloaded three.js into a directory named 'brick': git clone https://github.com/mrdoob/three.js.git which created a subdirectory: brick/three.js/ After navigating to brick/three.js/examples ...

Establish a connection to SQL Server using AngularJS

I recently started my journey in learning AngularJS and I am curious on how to establish a connection to SQL Server, retrieve data from it, and display it using AngularJS. Appreciate any help in advance! ...

What is the correct method for accessing an array within an object that is nested inside an array within a JSON file in Angular?

In my Angular controller code, everything is functioning properly except for the $scope.Product. I am unable to access the array of product details. Here is the relevant code snippet: .controller('aboutCtrl', function ($scope, aboutService) { ...

Stop the execution of jQuery ready handlers

I am facing a situation where I need to prevent jQuery ready handlers from firing on the DOMContentReady event under certain conditions. These handlers are set up in different places like include files, plugins, and more. While one approach could involve s ...

Unplanned pathways on a node-based server

Building a server, I've utilized the following code snippet: function uniqueString(length) { var result = ''; var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; for (var i = length; i &g ...

How can I make v-for display additional profiles to achieve an infinite scroll effect?

Hey there! I've got a Firestore database set up to fetch profiles and display them on a page using v-for. I want to implement infinite scroll for a smoother user experience. Here's the JavaScript composable code I'm working with: import { pr ...