UPDATE : find my answer here
A little clarity on getting key values using AngularFire v2?
I looked for many sources before asking a simple question but Im just sarting with firebase and I can't manage to use the data the way I want. What I need, is to retrieve two int in my controller (how much "yes" and how much "no" linked to a question.
the data model is the following
question/id/(text, yes, no)
I have a service where I call my data using an id
app.service('QuestionService', function($firebase,$q) {
var _this = this;
//initialize Firebase
var ref = new Firebase('https://basename.firebaseio.com/question');
this.get = function(nb){
var QuestionObject = ref.child(nb);
return $firebase(QuestionObject);
};
return this;
});
I have a controller function where I call some data using a random id
$scope.pickQuestion = function(){
var randomnumber = Math.ceil(Math.random() * 3);
$scope.message = QuestionService.get(randomnumber);
};
and then it works great so I can have something like
{{message.yes}} or {{message.no}} and get the corresponding integer.
My issue, what I want to do, is to pass this "message.no" value to my controller. I don't know what to do. I can't manage to get the value directly inside the controller (it works only inside the view) and I can't manage to pass the value to my controller from the view. I tried a
ng-init="functionName({{message.yes}}, {{message.no}})"
but it return an error into the console. (however the source a displayed correctly)
Does someone could guide me into the right direction?
Thanks
Related
I am refactoring an AngularJS application, and there, almost everything is stored in the $rootScope.
In my old applications I've build with Angular, I created a Service for each model, and then instantiated it within a Controller when needed.
I ask myself: Is it ok to store the whole user object inside the
$rootScope or what is best practice here?
How can I get sure to create a user during login and then pass it around throughout the whole application?
It seems ok generally storing user like models in $rootScope. But In my opinion it's not a best practise in angularjs(However I have used $rootScope way before).
Factory is the one of angularjs' beauty. Generally we use it to call rest services. But also you can create a model with it. Also you will be able to extend your model easily with injecting another model. That's just an idea , may be there is another better options to use model like objects in angularjs.
Lets look an example
// User Model
app.factory('User', function() {
var User = function(username) {
this.username = username;
this.email = null;
};
User.prototype.getDetails = function() {
var self = this;
return self.username;
};
return User;
});
// ExtendedUser Model
app.factory('ExtendedUser', function(User) {
var ExtendedUser = function() {
User.apply(this, arguments);
};
ExtendedUser.prototype = new User();
function getEmail() {
var self = this;
// You can make an http call to get email like information as an extra
self.email = "email#email.com";
return self;
}
ExtendedUser.prototype.getDetails = function() {
var self = this;
var extendedUser = getEmail();
return extendedUser;
};
return ExtendedUser;
});
I would look into a0-angular-storage: https://github.com/auth0/angular-storage It is great for storing user information / tokens or whatever to be retrieved throughout your app.
Key Features
Uses localStorage or sessionStorage by default but if it's not available, it uses ngCookies.
Lets you save JS Objects, If you save a Number, you get a Number, not a String
Uses a caching system so that if you already have a value, it won't get it from the store again.
If you don't want to store user model in $rootScope you can use private JS variable, which can be accessed by some service in Angular(since both factory and a service are singleton in Angular).
The nice addition is that it is harder to determine where the user model is stored, the only thing you need is proper encapsulation and code structure.
I'm using angular-fullstack to build a single page application, and in one of my controllers I'm trying to assign a user's id to a variable. The code
$scope.getCurrentUser = Auth.getCurrentUser;
returns
function () {
return currentUser;
}
This works fine for displaying in my view as my angular code can interpret the function and display the user id using {{getCurrentUser()._id}} which I'm assuming evaluates the promise and displays the code to the view.
My question is how do I assign $scope.getCurrentUser = Auth.getCurrentUser; to a variable in my controller? Whenever I do so, I get undefined variables. I've tried:
$scope.getId = Auth.getCurrentUser()._id;
console.log($scope.getId); //undefined
$scope.getId = Auth.getCurrentUser();
console.log($scope.getId._id); //undefined
I've read forum posts like this and this that explain that these methods are meant to be returned the way they are. Another post that is basically the same question as mine, but I'm still confused how to store the user id becuase the answer was hinting it was console.log that was the issue. Any help would be greatly appreciated, thanks.
Try the following and let me know how this works out:
angular.module('yourModuleName').controller('YourController', ['$scope', 'Authentication',
function($scope, Authentication) {
var authentication = Authentication;
$scope.getId = authentication.user._id;
console.log($scope.getId);
}
]);
Make sure Authentication is included in your controller.
i have a sortable table and after successfully moving an item i want to update all the rows in the databasetable which are effected from sorting.
my problem is that i dont know what's the best way to update multiple rows in my database with eloquent and how to send the data correct with angularjs
in angularjs i did this
//creating the array which i want to send to the server
var update = [];
for (min; min <= max; min++){
...
var item = {"id": id, "position": position};
update.push(item);
...
}
//it doesn't work because its now a string ...
var promise = $http.put("/api/album/category/"+update);
//yeah i can read update in my controller in laraval, but i need the fakeid, because without
//i get an error back from laravel...
var promise = $http.put("/api/album/category/fakeid", update);
in laravel i have this, but is there an possibility to update the table with one call instead of looping
//my route
Route::resource('/api/album/category','CategoryController');
//controller
class CategoryController extends BaseController {
public function update()
{
$updates = Input::all();
for($i = 0; $i<count($updates); $i++){
Category::where('id','=', $updates[$i]["id"])
->update(array('position' => $updates[$i]["position"]));
}
}
}
and yes this works but i think there are better ways to solve the put request with the fakeid and the loop in my controller ;)
update
k routing is solved ;) i just added an extra route
//angularjs
var promise = $http.put("/api/album/category/positionUpdate", update);
//laravel
Route::put('/api/album/category/positionUpdate','CategoryController#positionUpdate');
Try post instead put.
var promise = $http.post("/api/album/category/fakeid", update);
PUT vs POST in REST
PUT implies putting a resource - completely replacing whatever is available at the given URL with a different thing. By definition, a PUT is idempotent. Do it as many times as you like, and the result is the same. x=5 is idempotent. You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!
POST updates a resource, adds a subsidiary resource, or causes a change. A POST is not idempotent, in the way that x++ is not idempotent.
By this argument, PUT is for creating when you know the URL of the thing you will create. POST can be used to create when you know the URL of the "factory" or manager for the category of things you want to create.
so:
POST /expense-report
or:
PUT /expense-report/10929
I learned via using following
Laravel+Angular+Bootstrap https://github.com/silverbux/laravel-angular-admin
Laravel+Angular+Material https://github.com/jadjoubran/laravel5-angular-material-starter
Hope this help you understand how to utilize bootstrap & angular and speed up your develop by using starter. You will be able to understand how to pass API request to laravel and get callback response.
I am building an app for a client who has, as one of their data sets a master list of all their members. I have the data coming in from Firebase and everything runs peachy, but it's not that DRY I am now realizing. I would like to use some of the data from the membership set in other views within the site. I copied the code listed below into other controllers that I need to have access to it and although everything works, my IDE (RubyMine) shows the 'syncObject' as redundant.
So, my question is, if there's a way to code it better and dryer to be used in other views? Thank you for your time.
.controller( 'MembershipCtrl', function MembershipCtrl( $scope, $firebase ) {
var ref = new Firebase("https://myid.firebaseio.com/members");
var sync = $firebase(ref);
var syncObject = sync.$asArray();
$scope.members = syncObject;
});
I have been through several tutorials and posts about this topic and still can't seem to figure out what is wrong with my code. To me it seems I am having scoping issues with the data within my service. My code is split up into separate files. Here is my code:
github link : https://github.com/StudentJoeyJMStudios/PetPinterest.git
//in dataService.js
var app = angular.module('se165PetPinterestWebApp');
app.service('SharedData', function ()
{
var categoryOfSelectedAnimals = [];
this.setCatOfSelAnimals = function(pulledCategoriesFromParse)
{
categoryOfSelectedAnimals = pulledCategoriesFromParse;
console.log('after assignment in set::' + categoryOfSelectedAnimals);
};
this.getCatOfSelAnimals = function()
{
console.log('in get::::' + categoryOfSelectedAnimals);
return categoryOfSelectedAnimals;
};
});
in my first controller to set the data in signup.js
app.controller('SignupCtrl',['$scope', 'SharedData', function ($scope, SharedData)
{
var Categories = Parse.Object.extend('Categories');
var query = new Parse.Query(Categories);
query.find({
success: function(results)
{
$scope.availableCategoriesOfAnimals = results;
SharedData.setCatOfSelAnimals(results);
},
error: function(error)
{
alert('Error: ' + error.code + ' ' + error.message);
}
});
};
}]);
Then in my other controller trying to get the data from the array within my service:
var app = angular.module('se165PetPinterestWebApp');
app.controller('CatSelCtrl', function ($scope, SharedData)
{
$scope.availableCategoriesOfAnimals = SharedData.getCatOfSelAnimals();
});
When I print the contents from the SharedData.getCatOfSelAnimals I get 0 every time. Please help. Thank you very much in advance.
EDIT: After playing around with a string a bit I am finding the changed string in the set function is not saved into the service and when I call my get function within my service the string is not changed from the set method. Please help, thank you in advance.
EDIT: So it looks like when I navigate to new page by using window.location.href = '../views/categorySelection.html'; in my signup.js it reloads my dataService.js which re-sets my variables back to nothing. Does anyone have any ideas as to how to fix this?
Edit
First: why you lose data
You need to setup routing properly. Right now you are not changing views but rather using window.location.href to load a new bootstrap file (dashboard.html), i.e. everything saved in memory will be lost. So you have been doing it right, sort of, but the moment you change to dashboard.html all data from Parse is lost.
You can solve this by configuring routes and use $location.url() to change URL. Read more about angular.route here: https://docs.angularjs.org/api/ngRoute/service/$route
The angular way
After looking at your code and running your app I think we need to take a step back. Angular is tricky to get used to but there is a lot of good tutorials. I think you might wanna read some of them to get a better grasp of how it works and how to setup and build your app.
Start here: http://www.airpair.com/angularjs
Boilerplate
Found this boilerplate for an Angular app using Parse. It might be something you could use. https://github.com/brandid/parse-angular-demo
Original
Or an even quicker way to empty $scope.availableCategoriesOfAnimals and then merge new data without breaking reference:
$scope.availableCategoriesOfAnimals.length = 0;
Array.prototype.push.apply($scope.availableCategoriesOfAnimals, pulledCategoriesFromParse);
You are breaking the reference on assignment. This is a JavaScript issue, not an angular one for that matter ;)
Try this in your set function:
categoryOfSelectedAnimals.length=0;
pulledCategoriesFromParse.forEach(function (e) {categoryOfSelectedAnimals.push(e)});
in stead of reassigning
edit: angular extend works on objects, not arrays, so replaced it with a bit of JS.