Angularjs - Binding between controller and view - javascript

I am having problem with Angularjs view. Somehow i am doing something wrong and don't know where is the problem. Hope someone can help me out.
The problem is {{user.login}} (userRepoInfo.html file) does not get called at all from the controller and if i do console.log it is coming through fine from services. I am definitely doing something wrong between view and controller
I have five files
1) gitHubApiServices.js
2) gitHubApiController.js
3) userRepoInfo.html
4) app.js
5) index.html
Below 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">
Get my Repository
{{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>
Please help me out with this problem. I had spend couple of hours but no luck.
Thank you for your effort

I have tried your code with
{{user.login}}
instead of {{$scope.user.login}} in plinkr and it works fine. It returns my username (or any other info I request from GitHub RestFull Api.
You should not use $scope in the view. Angular wil lfigure out the proper scope for you and inject it to be used by the view.
Have a look at this plunkr: http://plnkr.co/edit/16yyngPoZBgzVvfyWCDq
P.S: I have flattened your folder structure for the sake of simplicity.

Related

angularjs firebase showing value in log but not in actual html

I hope this isn't gonna be too broad.
I have this simple angular website where I show data from firebase (...)
I fetch my data this way in the .js file:
'use strict';
angular.module('webApp.seeHoraire', ['ngRoute', 'firebase'])
.config(['$routeProvider', function($routeProvider){
$routeProvider.when('/seeHoraire', {
templateUrl: 'seeHoraire/seeHoraire.html',
controller: 'SeeHoraireCtrl'
});
}])
.controller('SeeHoraireCtrl', ['$scope', 'CommonProp', '$firebaseArray', function($scope, CommonProp, $firebaseArray){
var userId = firebase.auth().currentUser.uid;
console.log('Current user uid : ', userId);
return firebase.database().ref('/Users/' + userId + '/Horaire').once('value').then(function(snapshot) {
var lun1 = (snapshot.val() && snapshot.val().lun1) || 'X';
$scope.lun1 = lun1;
console.log($scope.lun1);
})
}])
This is logging me my "lun1" value perfectly fine, but when it comes to displaying it in my .html file, it shows nothing!
My .html file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="seeHoraire/seeHoraire.css" />
</head>
<body ng-controller="SeeHoraireCtrl">
<h1>{{lun1}}</h1>
</body>
</html>
Maybe I forgot something? Please help me.
Have a good day.
Maybe try:
$scope.$apply(function(){
$scope.lun1=lun1;
});
This was copied from: this link. Other answers there may also be helpful.

How to get data from rest api which has basic authentication?

I'm trying to get data from this website through HTTP get method. This website has basic authentication. The data is in JSON format.
This is the rest api website:
(https://shoploapi.herokuapp.com/sellers)
// Code goes here
angular.module('myapp', ['myapp.controller']);
angular.module('myapp.controller', ['myapp.service'])
.controller('testController', function($scope, testService) {
$scope.posts = {};
function GetAllPosts() {
var getPostsData = testService.getPosts();
getPostsData.then(function(post) {
$scope.posts = post.data;
}, function() {
alert('Error in getting post records');
});
}
GetAllPosts();
});
angular.module('myapp.service', [])
.service('testService', function($http) {
//get All NewsLetter
this.getPosts = function() {
return $http.get('https://shoploapi.herokuapp.com/sellers');
};
});
angular.module('myApp', ['base64'])
.config(function($httpProvider, $base64) {
var auth = $base64.encode("bhupendra7:ice123age456");
$httpProvider.defaults.headers.common['Authorization'] = 'Basic ' + auth;
});
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js#1.5.0" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-base64/2.0.5/angular-base64.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<h1>Hello Plunker!</h1>
<div ng-controller="testController">
<div>
<ul>
<li ng-repeat="post in posts">
{{post.careof}} {{post.district}} {{post.gender}} {{post.name}}
</li>
</ul>
</div>
</div>
</body>
</html>
Here's the link to my Plunker:
(https://plnkr.co/edit/7pqljm?p=preview)
Can anyone help?
There are 2 problems in your code.
1. You have a typo
In angular.module('myApp', ['base64']), change to module name to myapp
2. The way you have injected your myapp.controller to myapp module
Change it to angular.module('myapp', []); You will also need to reorder your code. Check out the Plunker I have created for you.
Even if you fix the above two problems, you will still face a CORS problem from Heroku. Depending on your server-side technology (NodeJS, Rails etc.), you will need to enable it from the server to be able to communicate with your app. You can also look in to JSONP with AngularJS
Hope this helps

AngularJS ui-router with templateProvider for A/B testing not rendering templates

I have created an angular app where I would like to randomly render two different homepage view when a user accesses the url.
I have created the app.js file with the following code using templateProvider to inject the testService which carries a pick function to return random selection of two arguments. This is below:
var myApp = angular.module('myApp', ['ui.router']);
myApp.service('testService', function(){
function pick() {
var i = Math.floor(Math.random() * arguments.length);
return arguments[i];
}
});
myApp.config(['$stateProvider','$urlRouterProvider', function($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateProvider: function(testService) {
var result = testService.pick('a', 'b');
return '<div ng-include="\'app/home-' + result + '.html\'"></div>';
}
});
$urlRouterProvider.otherwise('/');
}])
My index.html is below:
<html>
<head>
<title>Get Penta</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="https://unpkg.com/angular-ui-router/release/angular-ui-router.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp">
<ui-view></ui-view>
</body>
</html>
and my views
home-a:
<div>Version A</div>
home-b:
<div>Version B</div>
However none of the templates are rendered.
According to this article: https://github.com/angular-ui/ui-router/wiki
You can do this in several ways. I think your use of ng-include is failing, because basically this is done at page load time, and it's too late for that. I think a simple solution is to use the templateUrl, like this:
$stateProvider.state('home', {
templateUrl: function() {
function pick(){
var i = Math.floor(Math.random() * arguments.length);
return arguments[i];
}
var result = pick('a', 'b');
return 'app/home-' + result + '.html';
}
})

adding module not working

I am still in study mode of angularjs and just 2 day old. I was trying to make module and so i created seperate js file for it and created module like below.
Also added controller.
var app = angular.module("githubViewer", []);
app.controller("MainCtrl", MainCtrl);
But when i run i get error 'MainCtrl' is not a function, got undefined
here is Plunker
Can someone help me?
After looking in plunker,I think you want to create a separate module in separate file for your controllers and add it to your main module.
For that create module for controllers in separate file,
angular.module("githubViewer", [])
.controller('MainCtrl', function($scope,$http) {
//your logic
});
then add it to your main as dependency in main module
angular.module('plunker', ['githubViewer']);
here is working demo : http://plnkr.co/edit/T9p7Uo2DxUVjqS1wuuiA?p=preview
Ok, you're new to angular, so here's a couple of rules which you must follow until you can prove you need to do otherwise.
You can place definition of module in a separate file. In short plunkers it is often an overkill, but that's what you should be doing in realworld-sized apps. Note that I'm talking about only the module here. Not talking about controllers, factories and other stuff.
Separating body of controller from its inclusion into angular does not bring any benefit. Don't do that.
That said, your files should look like this:
# my_app.module.js
angular.module('myApp', []);
# main.controller.js
var app = angular.module('myApp')
app.controller('MainCtrl', MainCtrl);
function MainCtrl() {
// logic here
}
I check your Plunker.
here is Working Plunker as you want logic of controller in seperate js file and module in seperate file
app.js
function MainCtrl($scope,$http) {
var person = {
firstName: "Kiran",
lastName: "Nandedkar"
};
$scope.name = 'World';
var onUserComplete = function(response){
$scope.user = response.data;
}
var onError = function(reason){
$scope.error = "dfdfdf" ;
}
$http.get("https://api.github.com/users/odetocode")
.then(onUserComplete,onError);
$scope.person = person;
};
module.js
var app = angular.module("githubViewer", []);
app.controller("MainCtrl", MainCtrl);
index.html
<!DOCTYPE html>
<html ng-app="githubViewer">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.3/angular.js" data-semver="1.4.3"></script>
<script src="app.js"></script>
<script src="module.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{person.firstName}}!</p>
<div>Login : {{user.login}}</div>
</body>

$http.get succeeds; but can't access output?

How do I get the output from my remote server? - Firebug confirms that the JSON output is correct.
Here is my attempt, I have tried to be as standard as possible (Plnkr):
app.js, controllers.js, factories.js
'use strict';
var nameVersionFactory = angular.module('name.factories.version', []);
nameVersionFactory.factory('Version', ['$q', '$http', function ($q, $http) {
var d = $q.defer();
$http.get('/api').then(function (response) {
d.resolve(response);
});
return d.promise;
}]);
var nameVerCtrl = angular.module('name.controllers.version',
['name.factories.version']);
nameVerCtrl.controller(
'verCtrl', ['$scope', 'Version', function ($scope, Version) {
$scope.version = Version; /* {'status': 'online',
'rest_api_version': '1.1.14',
'server_time': '…'} */
}]
);
var nameApp = angular.module('name', ['name.controllers.version']);
/* CORS */
nameApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
Python REST API (30 lines): https://gist.github.com/anonymous/7d34867aca543911a06f
index.html
<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" id="ng-app" ng-app="name" lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div data-ng-controller="verCtrl">
<pre>{{version | json}}</pre>
<pre>{{version.status}}</pre>
<pre>{{version.data | json}}</pre>
<pre>{{version.data.status}}</pre>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js">
</script>
<script src="scripts/controllers.js"></script>
<script src="scripts/factories.js"></script>
<script src="scripts/app.js"></script>
</body>
</html>
Unfortunately I get no JSON output within those <pre>…</pre> tags.
Promises are no longer unwrapped automatically by scope variables in Angular 1.2+.
So, you have to do:
Version().then(function(result){
$scope.version = result;
});
Moreover, $http returns promises already, so this:
var d = $q.defer();
$http.get('/api').then(function (response) {
d.resolve(response);
});
return d.promise;
Can simply become:
return $http.get("/api");

Categories

Resources