AngularJS and Firebase not showing the $id - angularjs

I am trying to do an application that tracks attendees' approval of a speech or similar. I am facing a challenge which holds me off for now several hours.
Here is the js file
angular.module('speechAssessment', ['ngRoute', 'firebase'])
.value('fbURL', 'https://XXXX.firebaseio.com/')
.factory('Attendees', function($firebase, fbURL) {
return $firebase(new Firebase(fbURL));
})
.config(function($routeProvider) {
$routeProvider
.when('/', {
controller:'ListCtrl',
templateUrl:'partials/list1.html'
})
.otherwise({
redirectTo:'/'
});
})
.controller('ListCtrl', function($scope, Attendees) {
$scope.attendees = Attendees;
});
As you can see, I stripped the app to the bare minimum. I am getting data from Firebase and bring it into the $scope.attendees.
the html looks like
<div class="row">
<ul>
<li ng-repeat="attendee in attendees | orderByPriority">
<p>{{attendee.name}}:{{attendee.score}}:{{attendee.$id}}</p>
</li>
</ul>
</div>
I list all attendees and list some attributes, among them the $id from Firebase
So, a typical row looks like
roestigraben:-45:-JTI2DALNZXxltukIHcY
Now the application shows correct results until I remove the | orderByPriority filter. Doing so, the application runs but does not show the $id any longer. I cannot understand why this Filter has anything to do with the listing of the $id.
Can somebody shade some light on this for me, please. Really appreciated.

Related

Master detail in AngularJS

I try to write a small app that get a list from REST API and displays details for each selected item. I was looking for a simple tutorial on how to transfer the selected id from the list view to the detail view, but couldn't figure out. I assume I need to use the Master-detail technique.
Here's the code:
The list view:
<ul>
<li ng-repeat="gadgetDetails in gadgettDetails">
<div>
<p>{{gadgetDetails.type}}</p>
<p>{{gadgetDetails.manufacturer}}</p>
</div>
<hr />
</li>
</ul>
And the detail view
<div>
<p>Go back to Gadgets list</p>
<p>{{gadgetDetails[2].type}}</p>
<p>{{gadgetDetails[2].color}}</p>
<p>{{gadgetDetails[2].manufcturer}}</p>
</div>
So just for the question I've put 2 (the second object in the JSON list that I get from the REST API , but it actually should be gadgetDetails[i].type
but I couldn't figure out how to get the index (for example i) for each item in the list
This the controller:
GadgetListCtrl.controller('gdgtList', function($scope, $http, $filter) {
$http.get('https:.../gadgets.json').
then(function(response) {
$scope.gadgettDetails = response.data;
});
});
So the question is how to display for each item its details by the id.
Thanks
you can achive this by angular ui router params
below is dummy code
in .config block
$stateProvider
.state('gadgets', {
url: "/gadgets/:id",
templateUrl: 'gadgetDetail.html',
controller: 'gadgetController',
controllerAs: 'vm',
params: {
id: null
}
});
and in controller file, you can access the id as below
.controller('GadgetController', function($state, $stateParams) {
var selectedID = $state.params.id;
//alternatively you can get using $stateParams service
// $stateParams.id
if(selectedID) {
// get detail of gadget
}
});

AngularJS data binding and view change

I understand how two-way data binding works with AngularJS but I'm struggling to make it work in a situation described below. I've a index.template.html, home.template.html, search.template.html, app.js, search.controller.js and search.service.js files. I've a input form on a home page at '/' url.
<li ng-controller="searchCtrl"> //searchCtrl() in search.controller.js file
<form role="search">
<input type="text" ng-model="searchstring"
placeholder="Enter string here"> <br />
<button type="submit"
ng-click="searchString(searchstring)">Search</button>
</form>
</li>
And I've search.template.html to display the results as follows,
<html>
<body>
<h1> SearchedText</h1>
<h2> {{ searchedtext }} </h2>
</body>
</html>
search.controller.js is as follows,
(function () {
angular
.module('twowaybindapp')
.controller('searchCtrl', searchCtrl);
searchCtrl.$inject = ['$scope', 'SearchService'];
function searchCtrl($scope, SearchService) {
$scope.searchString = function(searchtext) {
SearchService
.getSearchResults(searchtext) //getSearchResults in search.service.js
.success(function(data) {
console.log('Service call is a success with result:');
console.log(data);
$scope.searchedtext = data;
}).error(function(e) {
console.log(e);
});
};
}
})();
My app.js file is as follows,
var myApp = angular.module('twowaybindapp', [ 'ngRoute' ]);
myApp.config(['$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.view.html'
}).
when('/search', {
templateUrl: 'search.view.html',
controller: 'searchCtrl'
}).
otherwise({ redirectTo: '/' });
}]);
With this background, When I've both form and results html text (content of search.template.html) in the same home.template.html, things work fine and I see all the results but if I put them in separate files as above, either I don't know how to open the results in new view after the call or don't know if data-binding is not working. I do see results in console.log() in both cases that mean service call is working okay as expected. This might be silly question but I really need help with this. Would it work if the search form is a part of navigation directive at the top of every page and results needs to be shown below in a main ng-view? Any help is appreciated. Thanks.
-- Atarangp
When you write {{smth}} in html it parsed to $scope.smth, each controller has its own scope object, by default scopes are nested:
<div ng-controller="c1" ng-init="smth = 1">
<div ng-controller="c2">
{{smth}} << 1
</div>
</div>
<div ng-controller="c3">
{{smth}} << undefined
</div>
When you defined several views - they will have different scopes, so you can not see one scope from another.
Fastest way to make it work is change to $rootScope.searchedtext = data; cause all your scopes nests from root scope.
Other way is to make common parent state and access and set your property there.
Yet another ways are: use your own service to store data, pass data using events, pass data using properties in state obj...

AngularJs - Unable to pass object using routeProvider

I load some data from the server, and then update the view using ng-repeat. The user has the ability to edit the data in another page. Now, is the part where I'm a bit confused. I can pass some parameters using $routeProvided combined with $routeParams, lets say id and fetch the data again from the server depending on that id. I believe there's a better way, something like passing the whole object to the next controller, rather than conducting another call the server. That's what I've got working right now:
app.config(function($routeProvider) {
$routeProvider
.when('/editPost/:postId/:author', {
templateUrl: 'editPost.html',
controller: 'editPostCtrl'
});
});
app.controller('editPostCtrl', function($scope, $routeParams) {
console.log($routeParams.author + ", " + $routeParams.postId);
});
Now, I cant extract the object with the following code:
HTML:
<div ng-repeat="post in posts">
<button class="btn" ng-click="editPost(post)">Edit</button>
</div>
JS:
app.config(function($routeProvider) {
$routeProvider
.when('/editPost/:post', {
templateUrl : 'editPost.html',
controller : 'editPostCtrl'
});
});
app.controller('editPostCtrl', function($scope, $routeParams) {
console.log($routeParams.post); //results in [object object]
});
Is there a better way for achieving this?

How to get current user from sails into an angular view

I have gotten a list of users from my sails back end into an angular view using $http. However, all I need is the information of the current user, and I need to access each attribute individually. Can someone provide for me an example of how I might go about this?
In api/controllers/UserController.js. This sails function returns the current user information in req.user.
module.exports = {
getUser: function(req,res) {
return res.send(req.user);
};
In config/routes.js. This is the route to the 'getUser' function in UserController.js.
'/getUser': {
controller: 'UserController',
action: 'getUser'
}
In assets/js/controllers.js, here is the $http request to the 'getUser' function in UserController.js. This is how you get the information from req.user into the front end.
angular.module('myApp.controllers', []).
controller('myCtrl', ['$scope', '$http', function($scope, $http) {
$http.get("http://localhost:1337/user/getUser").then(function(result) {
$scope.currentUser = result.data;
})
}]);
In assets/js/app.js, make sure your angular route is set to your view.
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view', {templateUrl: 'partials/view.html', controller: 'myCtrl'});
}]);
After putting this code (with your own variables/routes/server info) in the correct places, you can access the current user in your view like this
<div ng-controller="myCtrl">
{{ currentUser.email }} <br>
{{ currentUser.username }} <br>
{{ currentUser.etc }}
</div>
I searched the internet high and low for a week for an answer on how to do this and eventually came up with this. I see that a lot of people (on this site especially) have asked the same question, and I never really found a good, explicit answer. So I thought I would post what I've come up with as an answer to my own question.

Few basic questions troubling me related to AngularJS

I am developing demo application to learn AngularJS. Few things troubling me.
1 - What is the difference between
<div ng-controller="Page2Ctrl">
</div>
and
when('/page2', {templateUrl: 'views/flow1/page2.html', controller: 'Page2Ctrl'}).
Asking this because either is working fine. Is it necessary to define ng-controller in Html even if controller is defined in Routes?
2 - What is the difference between
function Page4Ctrl($scope){
$scope.pageName = "Page 4 loaded."
}
And
app.controller('Page4Ctrl', function ($scope) {
$scope.pageName = "Page 4 loaded."
});
second is verbose and need extra typing. Any suggestion on using them?
3 - Suppose I am developing a CRUD application for Customer. I make a CustomerController.js file where I want to put all the methods related to Customer (Create, Read, Update, Delete, FindById, FindAll etc). like below. Is this the right approach or controller should be one CustomerController which contains all the methods of CRUD?
app.controller('CustomerCreateController', function ($scope) {});
app.controller('CustomerEditController', function ($scope) {});
app.controller('CustomerDeleteController', function ($scope) {});
1) When typing the ng-controller directly to your view that view has a direct tie to that controller. Defining the controller in the route allows you to reuse the view for other needs.
For example, you have a view that displays a list of names.
<ul ng-controller="ListCtrl">
<li ng-repeat="item in items">{{item.name}}</li>
</ul>
Now someplace else in your application you have the same exact structure that displays a list of names you would need to do the same thing again.
<ul ng-controller="MyOtherListCtrl">
<li ng-repeat="item in items">{{item.name}}</li>
</ul>
If you remove the ng-controller attribute you can reuse this <ul/>
<ul>
<li ng-repeat="item in items">{{item.name}}</li>
</ul>
and
.when('/list1', {templateUrl: 'list.html', controller: 'ListCtrl'})
.when('/list2', {templateUrl: 'list.html', controller: 'MyOtherListCtrl'})
2) app.controller scopes the controller to your module while the other creates the controller on the global scope.
3) I depends how you have your application is structured, but Simply creating a CustomerController that has $scope methods for edit, delete, and create. This controller can take a dependency of a Service or $resoruce
app.controller('CustomerController', function ($scope, customerService) {
$scope.add = function(customer){
//add customer with customerService
};
$scope.edit = function(customer){
//edit customer with customerService
}
$scope.delete = function(customer){
//delete customer with customerService
}
});
If you want separate pages you could still reuse the same controller.
.when('/add', {templateUrl: 'add.html', controller: 'CustomerController'})
.when('/edit', {templateUrl: 'edit.html', controller: 'CustomerController'})
.when('/delete', {templateUrl: 'delete.html', controller: 'CustomerController'})

Resources