angularjs firebase showing value in log but not in actual html - javascript

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.

Related

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

How to put angular code in separate files

If I put this code below in one file it works good but when I separate, then don't work just show blank.In console I get error It can't find MainformCtrl.
Here is how I separated that:
app.js:
angular.module('notifications',['yaru22.angular-timeago','ngRoute'], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
angular.module('commentsApp',['notifications']);
angular.bootstrap(document.getElementById("comment"), ['commentsApp']);
commentsController.js
angular.module('commentsApp')
.controller('CommentsCtrl',function($scope,$http,$routeParams){
$scope.param = $routeParams.id;
$http.get("/api/comments/"+ $scope.param)
.success(function(data){
var details = [];
$.each(data,function(index,value){
if(value.user){
$.each(value.user,function(index1,value1){
var new_object = $.extend({}, value, value1);
details.push(new_object);
});
}
});
$scope.formShow = function(comm){
comm.formWhat = !comm.formWhat;
};
$scope.comments = details;
})
.error(function(data){
console.log(data);
});
})
.controller('MainformCtrl',function($scope){
$scope.fwhat = false;
$scope.MainFormShow = function(){
$scope.fwhat = !$scope.fwhat;
};
});
routes.js
angular.module('commentsApp')
.config(function($routeProvider,$locationProvider) {
$routeProvider.
when('/project/:id', {
controller: 'CommentsCtrl',
templateUrl: '/view/comments.html'
}).
otherwise({
redirectTo: '/'
});
//check browser support
if(window.history && window.history.pushState){
//$locationProvider.html5Mode(true); will cause an error $location in HTML5 mode requires a tag to be present! Unless you set baseUrl tag after head tag like so: <head> <base href="/">
// to know more about setting base URL visit: https://docs.angularjs.org/error/$location/nobase
// if you don't wish to set base URL then use this
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
}
});
Anyone know what is problem here?
Problem was because: module bootsrap. To solve that I deleted this:
angular.bootstrap(document.getElementById("comment"), ['commentsApp']);
from app.js
and added it on the end of controller file, because it is last file.
#Grundy thanks for help!
I've come to this problem too. :)
You just need to import them on your main html file. Don't forget the order of the elements. Here's how your HTML should look.
index.html
<html>
<head>
<link href="bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<!-- Here's your html stuff -->
<script src='angular.js'> <script>
<script src='app.js'> <script>
<script src='routes.js'> <script>
<script src='commentsController.js'> <script>
</body>
</html>
Don't forget to import your angular.js before your js files. Your css files should go on the head of the document and any Angular separated module should go right after angular.js. To use the $routeProvider, you need to import the ngRoute module and, to use this module, you need it's specific file. You can find it here or look to your specific version here.
Hope it help. :)
You can use something like Browserify or Webpack to require CommonJS style modules.

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>

Angularjs - Binding between controller and view

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.

AngularJs Model changes don't update

I have a model that I want to be editable, but for some reason nothing change, the textbox doesn't show up and the model is not being updated when using ng-view.
I can see the function enableEditor() being called using console.log.
If I write it inline instead of ng-view in the index.html without the profile.html everything works perfectly.
here are the files:
app.js
var proGamersApp = angular.module('proGamersApp', ['ngResource']).
config(function ($routeProvider) {
$routeProvider.
when('/', { controller: 'ProfileController', templateUrl: '/app/partials/profile.html' }).
otherwise({ redirectTo: '/' });
});
var ProfileController = function ($scope) {
$scope.init = function () {
$scope.title = 'first title';
};
$scope.init();
$scope.enableEditor = function () {
console.log('enableEditor()')
$scope.editorEnabled = true;
$scope.editableTitle = 'second title';
$scope.title = 'second title';
};
...
};
index.html
<!doctype html>
<html ng-app="proGamersApp">
<head>
<title>Pro Gamers</title>
<!-- Scripts -->
<script src="/app/lib/angular.min.js"></script>
<script src="/app/lib/angular-resource.js"></script>
<script src="/app/app.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
profile.html
<div ng-hide="editorEnabled">
{{title}}
Edit title
</div>
<div ng-show="editorEnabled">
<input ng-model="title" ng-show="editorEnabled">
Save
or
cancel.
</div>
Does someone know what I am doing wrong?
thanks
The link is adding to your address, causing the router to refresh the page and wack all your $scope vars. Instead of using blank anchors, use a span styled like an anchor:
span:hover {
cursor:pointer;
}
This only gives the cursor the pointer finger, customize the colors as you wish. Per your comments as well, don't add the target=_self to the href, add it after:
Save //prevent address bar change
As I said before though, use spans instead.

Categories

Resources