How to navigate object returned from AngularFire? - javascript

When I run the following Firebase query:
var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status');
data = $firebaseObject(ref);
console.dir(data);
I get the following object:
d
$$conf: Object
$id: "status"
$priority: null
Active, not recruiting: 39
Approved for marketing: 1
Completed: 339
Enrolling by invitation: 10
Not yet recruiting: 23
Recruiting: 128
Suspended: 3
Terminated: 38
Unknown: 74
Withdrawn: 15
__proto__: Object
I am trying to access the "Completed" element with value 339. However, console.log(data['Completed']) returns undefined. What is wrong?

A $firebaseObject starts out as an empty object, but when the data has been downloaded from the Firebase database, it then populates the object.
At first, you don't see anything because the data hasn't downloaded yet. Your console.log() runs a nanosecond after the $firebaseObject is created. The data is downloaded milliseconds after.
So you're probably asking, How do I handle the data if it doesn't exist at first?
What you can do is attach the $firebaseObject to $scope. And then bind it in your template. When the data downloads the Angular $digest loop runs, and refreshes your template.
Your controller would look like this:
app.controller('MyCtrl', function($scope, $firebaseObject) {
var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status');
$scope.data = $firebaseObject(ref);
});
Your template would look like this:
<div>Did you do it? {{ data.Completed }}</div>
There is another way, which takes a bit more setup, but it's my personal favorite. You can also use the router to resolve the data into the controller.
angular.module('app', ['firebase'])
.constant('FirebaseUrl', '<my-firebase-app>')
.service('rootRef', ['FirebaseUrl', Firebase])
.controller('MyCtrl', MyController)
.config(ApplicationConfig);
function ApplicationConfig($routeProvider) {
$routeProvider.when('/', {
controller: 'MyCtrl',
template: 'view.html',
resolve: {
data: function ($firebaseObject, rootRef) {
var ref = rootRef.child('companies/endo/status');
// a promise for the downloaded data
return $firebaseObject(ref).$loaded();
}
}
});
}
function MyController($scope, data) {
$scope.data = data;
console.log(data.Completed); // will work because the data is downloaded
}

Related

Another web service call inside ng-repeat

I have an angular application which I need to call web services. I have to call two different url to get data.
In my first url is like ==>
abc.com/student/3 this is the list of student. and another URL is
abc.com/parent/idofStudent3 when I pass student id of 3 in the second URL I need to get parent first name from the second URL.
I am able to retrieve the first URL data but I am unable to retrieve second URL data by passing first record data in ng-repeat. Could you please help me how to retrieve parent name in the web page?
Html Page
<h1 ng-repeat="x in myWelcome">
{{x.firstname}} || {{x.parentId}} </h1>
Here instead of displaying parentid I need to call another web service to display parent name by passing parentId as a parameter. how to call another web service here?
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("abc.com/student/3")
.then(function(response) {
$scope.myWelcome = response.data;
});
});
</script>
==> First webservice response is like :
{
"student":[
{
"name":"john",
"parentId": 12,
"address":"NYC"
},
{
"name":"Rohi",
"parentId": 14,
"address":"NJ"
},
]
}
==> second webservice response is like this when parentID=12:
{
"firstName": "Sr. John",
}
======> when parentIS 14
{
"firstName": "Sr. Rohi",
}
-------------------------
firstname || parentName
-------------------------
John || Sr. John
Rohi || Sr. Rohi
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.myWelcome = []
$http.get("abc.com/student/3")
.then(function(response) {
$scope.StudentData = response.data;
if($scope.StudentData){
$scope.myWelcome.push($scope.StudentData)
$http.get("abc.com/parent/$scope.StudentData.studentId")
.then(function(response) {
$scope.parentData = response.data;
$scope.myWelcome.push($scope.parentData)
});
}
});
});
</script>
I guess this might help you
Currently, you are searching for Parent details in the wrong scope object; myWelcome object is containing data from first service call, which returned list of student details only.
You can define a new scope object and bind data to it from second service call which will contain parent details; you can then use that object in ng-repeat.

Dynamically Creating Routes in Angular JS

We're trying to make the switch to angular, but we have a pretty big issue with routing. Our current site has something like 10,000 unique routes -- ever page has a unique ".html" identifier. There's no particular convention that would allow us to assign the controller to them, so I created a lookup API endpoint.
Here's the workflow I'm trying to create:
Angular app loads. One "otherwise" route is set up.
When someone clicks a link, I don't know if the resource is a product or a category, so a query is made to the lookup endpoint with the unique ".html" identifier. The endpoint returns two things: the name of the resource, and an ID ("product" and "10" for example). So to be clear, they hit a page like, "http://www.example.com/some-identifier.html," I query the lookup API to find out what kind of resource this is, and get a result like, "product" and "10" -- now I know it's the product controller/template and I need the data from product id 10.
The app assigns the controller and template ("productController" and "product.html"), queries the correct endpoint for data ("/api/product/10"), and renders the template.
The problems I'm facing:
$http isn't available during config, so I can't hit the lookup table.
Adding routes after the config is sloppy at best -- I've done it successfully by assigning $routeProvider to a global variable and doing it after the fact, but man, it's ugly.
Loading all the routes seems impractical -- just the size of the file would be pretty heavy for a lot of connections/browsers.
We can't change the convention now. We have 4 years of SEO and a lot of organic traffic to abandon our URLs.
I feel like I might be thinking about this the wrong way and there's something missing. The lookup table is really the problem -- not knowing what kind of resource to load (product, category, etc). I read this article about loading routes dynamically, but again, he's not making an external query. For us, loading the controllers isn't the problem, it's resolving the routes and then assigning them c
How would you solve the problem?
Solution
Huge thanks to #user2943490 for pointing me in the right direction. Don't forget to upvote his answer! I made it a little more general so that I don't have to define the route types.
API Structure
This configuration requires at least two endpoints: /api/routes/lookup/:resource_to_lookup:/ and /api/some_resource_type/id/:some_resource_id:/. We query the lookup to find out what kind of resource it points to and what the ID of the resource is. This allows you to have nice clean urls, like, "http://www.example.com/thriller.html" (a single) and "http://www.example.com/michaeljackson.html" (a collection).
In my case, if I query something like, "awesome_sweatshirt.html" my lookup will return a JSON object with "{type: 'product', id: 10}". Then I query "/api/product/id/10" to get the data.
"Isn't that slow?" you ask. With varnish in front, all of this happens in way less than 1 second. We're seeing pageload times locally of less than 20ms. Across the wire from a slow dev server was closer to half a second.
app.js
var app = angular.module('myApp', [
'ngRoute'
])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.otherwise({
controller: function($scope, $routeParams, $controller, lookupService) {
/* this creates a child controller which, if served as it is, should accomplish your goal behaving as the actual controller (params.dashboardName + "Controller") */
if ( typeof lookupService.controller == "undefined" )
return;
$controller(lookupService.controller, {$scope:$scope});
delete lookupService.controller;
//We have to delete it so that it doesn't try to load again before the next lookup is complete.
},
template: '<div ng-include="templateUrl"></div>'
});
$locationProvider.html5Mode(true);
})
.controller('appController', ['$scope', '$window', '$rootScope', 'lookupService', '$location', '$route', function($scope, $window, $rootScope, lookupService, $location, $route){
$rootScope.$on('$locationChangeStart', handleUniqueIdentifiers);
function handleUniqueIdentifiers (event, currentUrl, previousUrl) {
window.scrollTo(0,0)
// Only intercept those URLs which are "unique identifiers".
if (!isUniqueIdentifierUrl($location.path())) {
return;
}
// Show the page load spinner
$scope.isLoaded = false
lookupService.query($location.path())
.then(function (lookupDefinition) {
$route.reload();
})
.catch(function () {
// Handle the look up error.
});
}
function isUniqueIdentifierUrl (url) {
// Is this a unique identifier URL?
// Right now any url with a '.html' is considered one, substitute this
// with your actual business logic.
return url.indexOf('.html') > -1;
}
}]);
lookupService.js
myApp.factory('lookupService', ['$http', '$q', '$location', function lookupService($http, $q, $location) {
return {
id: null,
originalPath: '',
contoller: '',
templateUrl: '',
query: function (url) {
var deferred = $q.defer();
var self = this;
$http.get("/api/routes/lookup"+url)
.success(function(data, status, headers, config){
self.id = data.id;
self.originalPath = url;
self.controller = data.controller+'Controller';
self.templateUrl = '/js/angular/components/'+data.controller+'/'+data.controller+'.html';
//Our naming convention works as "components/product/product.html" for templates
deferred.resolve(data);
})
return deferred.promise;
}
}
}]);
productController.js
myApp.controller('productController', ['$scope', 'productService', 'cartService', '$location', 'lookupService', function ($scope, productService, cartService, $location, lookupService) {
$scope.cart = cartService
// ** This is important! ** //
$scope.templateUrl = lookupService.templateUrl
productService.getProduct(lookupService.id).then(function(data){
$scope.data = data
$scope.data.selectedItem = {}
$scope.$emit('viewLoaded')
});
$scope.addToCart = function(item) {
$scope.cart.addProduct(angular.copy(item))
$scope.$emit('toggleCart')
}
}]);
Try something like this.
In the route config you set up a definition for each resource type and their controllers, templates and a resolve:
$routeProvider.when('/products', {
controller: 'productController',
templateUrl: 'product.html',
resolve: {
product: function ($route, productService) {
var productId = $route.current.params.id;
// productService makes a request to //api/product/<productId>
return productService.getProduct(productId);
}
}
});
// $routeProvider.when(...
// add route definitions for your other resource types
Then you listen for $locationChangeStart. If the URL being navigated to is a "unique identifer", query the lookup. Depending on the resource type returned by the lookup, navigate to the correct route as defined above.
$rootScope.$on('$locationChangeStart', handleUniqueIdentifiers);
function handleUniqueIdentifiers (event, currentUrl, previousUrl) {
// Only intercept those URLs which are "unique identifiers".
if (!isUniqueIdentifierUrl(currentUrl)) {
return;
}
// Stop the default navigation.
// Now you are in control of where to navigate to.
event.preventDefault();
lookupService.query(currentUrl)
.then(function (lookupDefinition) {
switch (lookupDefinition.type) {
case 'product':
$location.url('/products');
break;
case 'category':
$location.url('/categories');
break;
// case ...
// add other resource types
}
$location.search({
// Set the resource's ID in the query string, so
// it can be retrieved by the route resolver.
id: lookupDefinition.id
});
})
.catch(function () {
// Handle the look up error.
});
}
function isUniqueIdentifierUrl (url) {
// Is this a unique identifier URL?
// Right now any url with a '.html' is considered one, substitute this
// with your actual business logic.
return url.indexOf('.html') > -1;
}
You can use $routeParams for this.
e.g.
route/:type/:id
so type and id can be totally dynamic, the different type handling will be up to the route's controller.
What if you have a json file with the information of the routes (and if there is not a security issue) and iterate over it to attach routes to the app?
e.g.
JSON:
routes: [
{
controller: "Controller1"
path: "/path1"
templateUrl: 'partials/home/home.html'
},
{
controller: "Controller1"
path: "/path1"
templateUrl: 'partials/home/home.html'
}
]
And then iterate over the contents of the JSON and attach them to $routeProvider.when ?
I am not sure if it is a good idea, depends how big would be the JSON file and if you dont want to expose all your routes to a possible attacker.
From the AngularJS documentation,
The $routeParams service allows you to retrieve the current set of
route parameters.
Dependencies: $route
Example look like
// Given:
// URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
// Route: /Chapter/:chapterId/Section/:sectionId
// Then
$routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
ngRouteModule.provider('$routeParams', $RouteParamsProvider);
function $RouteParamsProvider() {
this.$get = function() { return {}; };
}

Stop resolving controller data on search

Is there any way to stop resolving controller data if $location.search() is used.
Below is my code
App.config(function($routeProvider, $locationProvider) {
$routerProvider.when('/overview' {
title:"Overview",
controller:"OverViewCtrl",
templateUrl:"pages/overview.html",
resolve:{
mainData:function(Service){
return Service.getOverviewData();
}
});
});
In my controller I am using the same
App.controller("OverViewCtrl", function($scope, $location, mainData, Service){
$scope.data = mainData.data;
$scope.otherData = null;
Service.getOtherData($location.search(), function(data){
$scope.otherData = data;
});
$scope.search = function(param){
$location.search(param);
};
});
Each time search method is called mainData data is getting loaded from service, is there any way to call the getOtherData service on search.
$routeProvider configuration has reloadOnSearch property. From the documentation
[reloadOnSearch=true] - {boolean=} - reload route when only
$location.search() or $location.hash() changes.
Set it to false.
In your controller then subscribe to $route event $routeUpdate
$scope.$on('$routeUpdate',function(event,args) {
//Here you can get the other data.
});
Check the second argument to see what is passed in the args object hash. I believe it contains the current route and some other data.

Angular.js: Is .value() the proper way to set app wide constant and how to retrieve it in a controller

Hi there I was watching a couple of the angular.js videos and saw that the value() method was used to set a kind of module-wide constant. for example, one can set the Angular-UI library's config like so: (coffeescript)
angular.module('app',[])
.value "ui.config",
tinymce:
theme: 'simple'
width: '500'
height: '300'
And my app is currently looking like this:
window.app = angular.module("app", [ 'ui'])
.config(["$routeProvider", ($routeProvider) ->
$routeProvider
.when "/users",
templateUrl: "assets/templates/users/index.html"
controller: IndexUsersCtrl
.otherwise redirectTo: "/users"
])
.value 'csrf', $('meta[name="csrf-token"]').attr('content') #<---- attention here
IndexUsersCtrl = ($scope) ->
$scope.users = gon.rabl
console.log "I want to log the csrf value here" #<---- then attention
IndexUsersCtrl.$inject = ['$scope']
But I can't seem to get that value by tapping into the 'app' variable which is corresponding to the app module.
I read up here on ST and over on angularjs's google group that one way to share common code btwn controllers is through a service, will this concept apply here, too?
Thanks!
Module.value(key, value) is used to inject an editable value,
Module.constant(key, value) is used to inject a constant value
The difference between the two isn't so much that you "can't edit a constant", it's more that you can't intercept a constant with $provide and inject something else.
// define a value
app.value('myThing', 'weee');
// define a constant
app.constant('myConst', 'blah');
// use it in a service
app.factory('myService', ['myThing', 'myConst', function(myThing, myConst){
return {
whatsMyThing: function() {
return myThing; //weee
},
getMyConst: function () {
return myConst; //blah
}
};
}]);
// use it in a controller
app.controller('someController', ['$scope', 'myThing', 'myConst',
function($scope, myThing, myConst) {
$scope.foo = myThing; //weee
$scope.bar = myConst; //blah
});
I recently wanted to use this feature with Karma inside a test. As Dan Doyon points out the key is that you would inject a value just like a controller, service, etc. You can set .value to many different types - strings, arrays of objects, etc. For example:
myvalues.js a file containing value - make sure it is including in your karma conf file
var myConstantsModule = angular.module('test.models', []);
myConstantModule.value('dataitem', 'thedata');
// or something like this if needed
myConstantModule.value('theitems', [
{name: 'Item 1'},
{name: 'Item 2'},
{name: 'Item 3'}
]);
]);
test/spec/mytest.js - maybe this is a Jasmine spec file loaded by Karma
describe('my model', function() {
var theValue;
var theArray;
beforeEach(module('test.models'));
beforeEach(inject(function(dataitem,theitems) {
// note that dataitem is just available
// after calling module('test.models')
theValue = dataitem;
theArray = theitems;
});
it('should do something',function() {
// now you can use the value in your tests as needed
console.log("The value is " + theValue);
console.log("The array is " + theArray);
});
});
You need to reference csrf in your controller IndexUsersCtrl = ( $scope, csrf )
IndexUsersCtrl.$inject = [ '$scope', 'csrf' ]

AngularJS - Pass parameters into Controller?

I'm trying to create a simple blog website using AngularJS. I'm just starting out, so what I'm thinking my not be the best way to do this, so any alternative suggestions are welcome.
I have a controller.js file with two blog controllers. One to display a list of blog posts, and the other that displays the post content by including an HTML file.
controller.js
myAppControllers.controller('BlogListCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get('articles/articles.json').success(function (articles) {
$scope.articles = articles;
});
}]);
myAppControllers.controller('BlogPostCtrl', ['$scope', '$routeParams', function ($scope, $routeParams) {
$scope.includeFile = 'articles/' + $routeParams.blogPostId + '.html';
}]);
articles.json
[
{
"id": "test-article-one",
"title": "Test Article one",
"author": "Gareth Lewis",
"datePosted": "2015-06-23",
"summary": "This is a test summary"
},
{
"id": "test-article-two",
"title": "Test article two",
"author": "Gareth Lewis",
"datePosted": "2015-06-23",
"summary": "This is a test for article two"
}
]
app.js
when('/blog', {
templateUrl: 'partials/blog-articles.html',
controller: 'BlogListCtrl'
}).
when('/blog/:blogPostId', {
templateUrl: 'partials/blog-post.html',
controller: 'BlogPostCtrl'
}).
blog-post.html
<ng-include src="'partials/header.html'"></ng-include>
<!-- Want to add title, author, datePosted information here... -->
<article class="content">
<ng-include src="includeFile"></ng-include>
</article>
This blog listings work fine. When I click into a blog post, it also serves up the content from the HTML file OK as well. However, I want to be able to reuse the title, author and datePosted properties from the selected article in the blog-post.html partial view. What's the best way to do this? Would I need to pass them to the Controller somehow to then pass to the view? I don't really want to pass these as routeParams. Or would I need to do a $http.get on articles.json and iterate through to find the selected article and then pass the property values back to the view?
Thanks for the help.
You said that suggestions are welcome, so here it goes.
1 - Transport all your Blog logic to a service;
2 - Provide the data on resolving routes. This is a better approach to handle errors during the load time, 404s, and so on. You can provide a listener to $routeChangeError and deal with it there;
3 - On the service declared below, you have the methods to call your data and a method to retrieve the list cached on the service:
// services.js
myAppServices
.service('BlogService', ['$http', '$q', function ($http, $q) {
var api = {},
currentData = {
list: [],
article: {}
};
api.getSaved = function () {
return currentData;
};
api.listArticles = function () {
var deferred = $q.defer(),
backup = angular.copy(currentData.list);
$http.get('articles/articles.json')
.then(function (response) {
currentData.list = response;
deferred.resolve(response);
}, function () {
currentData.list = backup;
deferred.reject(reason);
});
return deferred.promise;
};
api.getArticle = function (id) {
var deferred = $q.defer(),
backup = angular.copy(currentData.article),
path = 'articles/' + id + '.html';
$http.get(path, {
cache: true
})
.then(function (response) {
currentData.article = {
path: path,
response: response
};
deferred.resolve(currentData.article);
}, function (reason) {
currentData.article = backup;
deferred.reject(currentData.article);
});
return deferred.promise;
};
return api;
}]);
The BlogService.getSaved() will retrieve the stored data, made after each call.
I've made a method to call the ng-include path too, so you can verify if it exists, with cache === true, the browser will keep a copy of it, when calling it again on the view. A copy of the response of the blog article is made too, so you can access its path and the response whenever you need.
On the controllers below, they were adaptated to supply the current needs:
// controller.js
myAppControllers
.controller('BlogListCtrl', ['$scope', 'articles',
function ($scope, articles) {
$scope.articles = articles;
/* OTHER STUFF HERE */
}
])
.controller('BlogPostCtrl', ['$routeParams', '$scope', 'article' 'BlogService',
function ($routeParams, $scope, article, BlogService) {
// On `article` dependency, you have both the original response
// and the path formed. If you want to use any of it.
$scope.includeFile = article.path;
// To get the current stored data (if any):
$scope.articles = BlogService.getSaved().list;
// Traverse the array to get your current article:
$scope.article = $scope.articles.filter(function (item) {
return item.id === $routeParams.id;
});
/* OTHER STUFF HERE */
}
]);
And the route declarations were changed to load the data when resolving the routes.
// app.js
$routeProvider
.when('/blog', {
templateUrl: 'partials/blog-articles.html',
controller: 'BlogListCtrl',
resolve: {
articles: ['BlogService', '$routeParams', function (BlogService, $routeParams) {
return BlogService.listArticles();
}]
}
})
.when('/blog/:id', {
templateUrl: 'partials/blog-post.html',
controller: 'BlogPostCtrl',
resolve: {
article: ['BlogService', '$routeParams', function (BlogService, $routeParams) {
return BlogService.getArticle($routeParams.blogPostId);
}]
}
})
This is maybe a common question in angular. What you have to understand is that Scope is defined per controller... In order to share data across controller you still have the option to use $scope.$parent or $rootScope to link controllers but I would use those carefully.
It is better to use Angular Services which are based on singleton patterns therefore you can use them to share information between controllers and I think it will be a better approach.
I found that this has been previously discussed and here are some good examples:
AngularJS Service Passing Data Between Controllers
You can use a global scope to set this data, or you can use service to communicate between the controllers. There is a lot of ways to resolve this problem read a little bit more about services in the link bellow and see if you can find how to resolve your problem.
AngularJS: Service vs provider vs factory

Categories

Resources