AngularJS - Establishing communication between controller and view

I am facing an issue with the Angularjs view. I seem to be making a mistake somewhere and I can't figure out where the problem lies. I hope someone can assist me with this. The problem is that {{user.login}} (userRepoInfo.html file) is not being called at all from the controller, even though I can see the data coming through fine from the services when I use console.log. There seems to be an error in communication between the view and the controller.

I have the following five files:
1) gitHubApiServices.js 
2) gitHubApiController.js
3) userRepoInfo.html
4) app.js
5) index.html

Here is gitHubApiServices.js

(function() {
                var gitHubApiFactory = function($http) {

                    var factory = {};
                    factory.getUserName = function(userName) {
                        console.log(userName + " " + "This is from Services")
                        return $http.get("https://api.github.com/users/" + userName);
                    };
                    return factory;
                };

                gitHubApiFactory.$inject = ['$http'];

                angular.module('gitHubApp').factory('gitHubApiFactory',gitHubApiFactory);

            }());

Below is gitHubApiController.js

 (function() {

            var gitHubInfoController = function ($scope,gitHubApiFactory) {
                $scope.user = null;
                $scope.gitHubUser = function(userName) {
                    gitHubApiFactory.getUserName(userName)
                        .success(function (data) {
                            $scope.user = data;
                            console.log(data);
                        })
                        .error(function(data, status, headers, config) {
                            $log.log(data.error + ' ' + status);
                        });
                }
            };

            gitHubInfoController.$inject = ['$scope','gitHubApiFactory'];

            angular.module('gitHubApp')
                .controller('gitHubInfoController', gitHubInfoController);
        }());

Below is userRepoInfo.html

 <div data-ng-controller="gitHubInfoController">
                <h1>Github App</h1>
                <input type="text" id="gitUserName" ng-model="gitUser" placeholder="Please enter your GitHub Username">
                <a href="#" id="getUserRepo" ng-click="gitHubUser(gitUser)">Get my Repository</a>

                {{user.login}}
            </div>

Below is app.js

(function() {

    var app = angular.module('gitHubApp', ['ngRoute']);

    app.config(function($routeProvider) {
        $routeProvider
            .when('/', {
                controller: 'gitHubInfoController',
                templateUrl: 'app/views/userRepoInfo.html'
            })
            .otherwise( { redirectTo: '/' } );
    });

}());

Below is index.html

<!doctype html>
<html data-ng-app="gitHubApp">
<head>
    <title>Github Repository App</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

    <div data-ng-view></div>


<script src="vendor/angular.js"></script>
<script src="vendor/angular-route.js"></script>
<script src="app/app.js"></script>

<script src="app/controllers/gitHubApiController.js"></script>
<script src="app/services/gitHubApiServices.js"></script>
</body>
</html>

I would greatly appreciate any help with this issue. I have been trying to solve it for a few hours with no success.

Thank you for your assistance

Answer №1

I tested your code using {{user.login}} instead of {{$scope.user.login}} in Plinkr and it worked perfectly. It displayed my username and any other information requested from the GitHub RestFull API.

Avoid using $scope in the view. Angular will determine the appropriate scope and inject it for view use.

Check out this Plunkr example: http://plnkr.co/edit/16yyngPoZBgzVvfyWCDq

NOTE: I simplified your folder structure for ease of understanding.

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

I utilized the "data-target" attribute to ensure the active link retains its style. Is there a way to preserve the style when navigating away from an active link?

Can someone assist me with this re-upload? I need help tweaking my code to maintain style when navigating between pages using the "data-target" attribute. Currently, the style is being lost when moving from the original link (e.g., "link/sub01.html") to a ...

Navigating router queries within Nuxt: A step-by-step guide

One of the challenges I am facing is passing value parameters in my URL with the mounted function looking like this: mounted () { this.$router.push({ path: '/activatewithphone', query: { serial: this.$route.params.serial, machin ...

What is the process of uploading files using Ajax?

Can anyone help me with submitting a form using ajax that contains images? I have this code snippet which logs an object called "FormData" in the console, but I'm not sure how to properly use it or retrieve it. Is this the correct approach? $("#form_ ...

Using Internet Explorer to watch full-screen HTML 5 videos

I am in the process of developing my own HTML 5 Browser Player. Everything seems to be working well, except for getting the full screen feature to function properly in IE 10. Chrome, Safari, and Firefox are all doing great with it. Unfortunately, my JavaS ...

Failure of window marker to trigger click event in jquery-bing-maps

I'm encountering an issue where clicking on links within Window markers on Bing Maps redirects me to a new page instead of triggering a JavaScript event as intended. $('.single_address').on('click', function (evt) { alert(&apo ...

Modifying the key of a JSON object can result in the alteration of other associated values as well

Overview: A JSON Object var JSON_OBJECT = []; has been defined as a global variable. [ { "user_id": "123", "AF": [ { "formula_type": 0, "lag": 0 } ], "Trend": [ { "is_active": 0 ...

What is the best method for clearing all session cookies in my React application?

Currently, I am working on a project using React. I am trying to find a method to automatically logout the user by deleting all of the session cookies in my React application. However, I have not been able to come up with a solution yet. Is there a way to ...

tips for recognizing the location of an item in an array

When loading an array of objects into a select box, how can I identify which object the user has selected so that I can use it for further work? For instance, if the user chooses the 2nd object in the array, how do I know that their selection corresponds ...

Swapping out characters that are not numerical within a text input field

Is there a way to restrict the input in a text box to only numbers (1-5), a $(dollar) .(decimal) and '(singlequote) during a keyup event? I need a method that will replace any characters typed that are not part of this criteria with a *. Can you pleas ...

"Ensuring function outcomes with Typescript"Note: The concept of

I've created a class that includes two methods for generating and decoding jsonwebtokens. Here is a snippet of what the class looks like. interface IVerified { id: string email?: string data?: any } export default class TokenProvider implements ...

modify the b-form-checkbox component in a Vue application

I have inserted the <b-form-checkbox> element into a <b-table>: https://jsfiddle.net/fmattioni/L269rd7s/ This is my current objective: 1 - Initially, all checkboxes in the table are checked using checked="true". 2 - Try unchecking ...

Troubleshooting the issue with ajax loadXml callback functionality

My table is empty and I can't figure out where the mistake is. I want to use the console to debug, but I'm not sure how. Update: I found a working sample here http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2. I used similar code, bu ...

Fan Animation in CSS

I have three unique images that I would like to animate in a fan-like manner consecutively. I prefer not to merge the images in Photoshop, as I want them to be displayed one after the other. Here is the code snippet (dummy images are used): .bannerimg ...

Retrieve data from a single PHP page and display it on another page

In my project, I am working with three PHP pages: index.php, fetch_data.php, and product_detail.php. The layout of my index.php consists of three columns: filter options, products panel, and detailed description. Whenever a user clicks on a product in th ...

Unable to make getJSON function properly with CodeIgniter

I'm experimenting with using getJSON to retrieve the most recent data from my database. So far, I've stored it in an array and used json_encode(the array). This method successfully displays the information on the view, but the problem lies in the ...

Work with JSON array objects

I am a novice in javascript and JSON. I have a requirement to process each JSON object, as shown in the example prototype below. Can someone please assist me in solving this problem? I need to log each room number given in the JSON sample below. How can I ...

What is the process of transforming a tree into a JSON object?

I have a tree structure that I need to convert into JSON format for use with a jquery option tree. NodeId, Title, Level 1, cars, 0 2, boats, 0 3, oldtimer, 1 4, trucks, 1 5, heavytrucks, 4 The desired tree structure is as follows: boats cars - oldtimer - ...

I keep encountering an error in the where clause when trying to update MySQL. What could be

I encountered an issue stating Unknown column 'CR0001' in 'where clause' while executing my code. Strangely, the error seems to be related to the id_scooter column rather than CR0001. Below is the snippet of my code: var update = "UPDA ...

`Is there a specific location for this code snippet?`

Recently, I stumbled upon a script that enables website screen scraping. For instance, you can check out an example on JsFiddle The issue arises when I attempt to incorporate another script from "Embed.ly" This specific script enhances a provided link and ...

Prepare for a thorough cross-referencing session

In my attempt to create a tool with 3 inputs that are interdependent - "Earn %", "Earn $" and "Own Price". Initially, the default value for "Earn percentage" is set at "10", making the initial calculation function as intended. Changing this one value auto ...