angularjs - Trying to scope the users information -
i need use current user id filter on ng-repeat. i'm still trying grasp on angular, assumption may wrong. thinking if can put current users information (name, id, email etc) in scope, can use scope insert id filter in angular controller.
so i've created users_controller.rb
def index respond_with current_user end
so shows current user information.
i've added resource routes.rb
resources :users
then created factory retrieve json information in userservice.js
.factory('userservice', [ '$http', function($http) { return { loadusers: function() { return $http.get(('/users.json'),{ cache: true}). success(function (data, status, headers, config) { if (status == 200) { console.log('succes') } else { console.error('error happened while getting user list.') } }) } }; } ])
then console log in browser says succes
, i'm assuming it's retrieving data users.json file.
and in maincontroller.js
created function saves response data factory service in scope
userservice.loadusers().then(function(response) { $scope.users = response.data; }); console.log ($scope.users)
but console.log
gives result of undefined
. first question is, know why i'm getting undefined
instead of information of current user.
my second question is, if work out first problem , can store information in $scope.users
possible use information in controller so?
var user_id = $scope.user.id $scope.user_id = user_id;
your first question:
angularjs asynchronous, follows $http
service asynchronous, getting undefined (because console.log
run before $http
service completed)
your second question:
if using $scope.user_id
(which assumption stores current user id? isn't defined elsewhere) filter (which fine, although might need define own since it's bi vague in question), you'll need assign inside $http
service (not outside). or can chain promise assign after $http
request has been completed. although in opinion, if using current user id filter out array of users, shouldn't use ng-repeat
, tell angularjs use custom filter. angularjs create bunch of watchers each element in ng-repeat
, lot of other things keep track in case of events in dom or script change view. (which i'm guessing won't)
if i'm right that, should manually filter out using angular.foreach
or for
loop , have sent view
Comments
Post a Comment