Firebase / Angular JS show only firebase entries created by logged in user - javascript

Right now I have a table that is currently showing all the entries form an "events" node in firebase.
However, I only want to show the events created by the logged in user. Right now they are showing events created by all users.
I'm guessing I might be able to use an ng-if directive after the ng-repeat in the tag, however, I am not sure what to put into it.
This is my table:
<table class="table table-striped">
<thead>
<tr>
<th>Title</th><th>Location</th> <th>Actions</th>
</tr>
</thead>
<tbody>
<tr scope="row" ng-repeat="event in events | reverse" >
<td>{{event.title}}</td>
<td>{{event.location}}</td>
<td><button class="btn btn-primary" ng-click="events.$remove(event)"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button></td>
</tr>
</tbody>
The user object looks like so:
{
"provider": "password",
"uid": "635gt3t5-56fe-400d-b50b-1a6736f8874a",
"token":
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6Im1pY2hhZWwubGFyaXZpZXJlMTk3M0BnbWFpbC5jb20iLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImlhdCI6MTQ2OTEyNTYyOSwidiI6MCwiZCI6eyJwcm92aWRlciI6InBhc3N3b3JkIiwidWlkIjoiNmY5ZmM0NTUtNTZmZS00MDBkLWI1MGItMWE2NzM2Zjg4NzRhIn19.yIzzV7Or7tUlXi-sSWeioNx6LLoQ0U9qnW1X06rpSmA",
"password": {
"email": "xxxxxx.xxxxxx1234#gmail.com",
"isTemporaryPassword": false,
"profileImageURL": "https://secure.gravatar.com/avatar/5f9effbf8cbea69792c595079cf25d38?d=retro"
},
"auth": {
"provider": "password",
"uid": "635gt3t5-56fe-400d-b50b-1a6736f8874a",
"token": {
"email_verified": false,
"email": "xxxxxx.xxxxxx1234#gmail.com",
"exp": 1469212029,
"iat": 1469125629,
"sub": "635gt3t5-56fe-400d-b50b-1a6736f8874a",
"auth_time": 1469125629,
"firebase": {
"identities": {
"email": [
"xxxxxx.xxxxxx1234#gmail.com"
]
}
}
}
},
"expires": 1469212029
}
My controller looks like this:
angular.module('myApp').controller('ChatCtrl', function($scope, user,
Ref, $firebaseArray, $timeout) {
console.dir('user: ' + JSON.stringify(user));
// synchronize a read-only, synchronized array of events, limit to most recent 10
$scope.events = $firebaseArray(Ref.child('events').limitToLast(10));
// display any errors
$scope.events.$loaded().catch(alert);
// provide a method for adding a event
$scope.addEvent = function(newEvent) {
if (newEvent) {
// push a event to the end of the array
$scope.events.$add({
title: newEvent.title,
location: newEvent.location,
createdBy: user.uid,
createdAt: Firebase.ServerValue.TIMESTAMP
})
// display any errors
.catch(alert);
}
};
function alert(msg) {
$scope.err = msg;
$timeout(function() {
$scope.err = null;
}, 5000);
}
});
This is what the users and events look like in firebase:

To get the results that you're looking for, try using an angularjs filter.
In you controller add a function called
$scope.filterByUID = function(event) {
if (event.createdBy === user.uid) {
return true;
}
return false;
}
This function will act as a filter that only let's through events that were created the current user by comparing the event's createdBy to the user's uid.
Then change this line in your html
<tr scope="row" ng-repeat="event in events | reverse" >
To
<tr scope="row" ng-repeat="event in events | reverse | filter:filterByUID" >
This tells angularjs that you want to have your items filtered with the filter we defined in the controller.
Edit: Here's a reference on using custom filters: AngularJS : Custom filters and ng-repeat

Related

ng-repeat not populating table

I've populated a table with data from a JSON file, and then when the user clicks on an item in the table, a container and it's fields display below and it SHOULD be populated with that specific data, though it isn't.
The function select is invoked through list-patents.htm which contains the table with a list of patents. I have used the $rootScope object so the function is accessible from multiple controllers i.e. patentDetailsCtrl
Why isn't my table in patent-item.htm being populated with the ng-repeat directive?
var app = angular.module('myApp', ['ngRoute', 'angularMoment', 'ui.router', "chart.js"]);
$stateProvider
.state("patents.list.item", {
url: "/patent-item",
templateUrl: "templates/patents/list/patent-item.htm",
params: {
id: null,
appNo: null,
clientRef: null,
costToRenew: null,
renewalDueDate: null,
basketStatus: null,
costBandEnd: null,
nextStage: null
},
controller: "patentDetailsCtrl"
})
app.run(function($rootScope) {
$rootScope.select = function() {
return $rootScope.patentItem = item;
}
});
app.controller('patentDetailsCtrl', ['$scope', '$http', function($scope, $http) {
$scope.selectedPatent = $scope.patentItem;
console.log($scope.selectedPatent);
}]);
list-patents.htm
<tbody>
<tr ng-repeat="x in patents">
<td ng-click="select(x)"><a ui-sref="patents.list.item({id: x.id, appNo: x.applicationNumber, clientRef: x.clientRef, costToRenew: x.costToRenew, renewalDueDate: x.renewalDueDate, basketStatus: x.basketStatus, costBandEnd: x.costBandEnd, nextStage: x.nextStage})">{{x.applicationNumber}}</a></td>
<td ng-bind="x.clientRef"></td>
<td ng-bind="x.costToRenew">$</td>
<td ng-bind="x.renewalDueDate"></td>
<td><button type="button" class="btn btn-danger" ng-click="remove(x.id)">Remove</button></td>
</tr>
</tbody>
patent-item.htm
<table>
<tbody>
<thead>
<tr>
<td>applicationNumber</td>
<td>clientRef</td>
<td>costToRenew</td>
<td>renewalDueDate</td>
<td>basketStatus</td>
<td>costBandEnd</td>
<td>nextStage</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in selectedPatent">
<td>{{x.applicationNumber}}</td>
<td>{{x.clientRef}}</td>
<td>{{x.costToRenew}}</td>
<td>{{x.renewalDueDate}}</td>
<td>{{x.basketStatus}}</td>
<td>{{x.costBandEnd}}</td>
<td>{{x.nextStage}}</td>
</tr>
</tbody>
</table>
</tbody>
You need to correct below points:
your $rootScope.select() method doesn't accept data (select(x)) passed from your list-patents.htm, So put item as param.,
Like : $rootScope.select = function(item) { \\ code
Sine you do ng-repeat on $rootScope.patentItem, then I guess you need to make it array, and push the passed data to it. (No need of return statement as well.)
So run block should be like :
app.run(function($rootScope) {
rootScope.patentItem = [];
$rootScope.select = function(item) {
$rootScope.patentItem.push(item);
}
});
See this Example Fiddle
To me it seems like you're trying to access the patentItem selected in your select function. If you're passing it to the $rootScope this way, you will also need to access it this way.
So change the line as follows...
$scope.selectedPatent = $rootScope.patentItem

AngularJS can not read property id of undefined Error

I am getting the error "can not read property id of undefined" in AngularJS.
We have two API End point,
i> GET http://127.0.0.1:8088/api/information/ to fetch the data from JSON.
ii> DELETE http://127.0.0.1:8088/api/information/:id to delete the data of that particular id.
I have created a table, where datas will display in row. There is a checkbox to select row and a Delete button.
I am performing three operations,
i> Ftech the data in table.
ii> Click on checkbox to select that row.
iii> Click on the DELETE button to delete that data from display and hit the DELETE api end point to delete from server too.
iv>Refresh the page and fetch the data again.
Here is the JSON :-
{
"1": {
"venture": "XYZ Informatics",
"member": [
{
"name": "abcd",
"email": "abcd#gmail.com"
}
],
"message": "This is good day",
"isclicked": false
},
"2": {
"venture": "BBC Informatics",
"member": [
{
"name": "xyz",
"email": "xyz#gmail.com"
}
],
"message": "This is bad day",
"isclicked": true
}
}
Here is the code :-
<!DOCTYPE html>
<html ng-app="MyApp">
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
</style>
</head>
<body>
<div ng-app="MyApp" ng-controller="displayController">
<table style="width:100%">
<tr ng-repeat="data in datas">
<td>
<input type="checkbox" ng-model="data.clicked">
</td>
<td>{{ data.id }}</td>
<td>{{ data.venture }}</td>
<td>{{ data.message }}</td>
</tr>
</table>
<button ng-click="delete()">DELETE</button>
</div>
<script>
angular.module('MyApp', [])
.controller('displayController', function($scope, $http) {
var url = "http://127.0.0.1:8088/api/information";
$http.get(url).success(function (response) {
$scope.datas = response;
});
//To Delete
$scope.delete=function(){
angular.forEach($scope.datas, function(val, key){
if(val.clicked){
delete $scope.datas[key]
var userId = $scope.data.id; //It is coming from {{ data.id }}
$http.delete('http://127.0.0.1:8088/api/information/:' + userId) //DELETE API end point
.success(function (response) {
$scope.refresh(); //Refresher function
});
$scope.refresh = function(){
var url = "http://127.0.0.1:8088/api/information"; //Fetch the updated data
$http.get(url).success(function (response) {
$scope.datas = response;
});
}
}
})
}
});
</script>
</body>
</html>
Not near a computer to properly test your code, but a first read left me with this: When you do delete $scope.datas[key], you are destroying the data object. So when you try to assign userId, the object you are trying to access doesn't exist. My recommendation would be to only do a local item removal on a successful server DELETE. Try moving delete $scope.datas[key] into the success function.
On a separate note, .success() is deprecated, and it is preferred to use the ES6 Promise compliant .then(successfn, errorfn) form. See more here.

how to update nested json array using meteor.js

I am want to insert these values into mongodb and here is my code, i am able to insert it but when i was updating only access_policy inside admin_section, i was not able to do that, can anyone please help me, how can i solve it :
meteor.json
{
"_id" : ObjectId("555ebffa7c88507a4a683e81"),
"section_id" : "Admin Section",
"is_active" : true,
"admin_section" : [
{
"_id" : 1,
"info" : "Setup custom access policy for user groups",
"sub_section" : "Setup - access policy",
"access_policy" : "ROOT"
},
{
"_id" : 2,
"info" : "Customize access policy for main sections",
"sub_section" : "Manage - access policy",
"access_policy" : "ROOT"
},
{
"_id" : 3,
"info" : "Manage user groups for DX-Client application",
"sub_section" : "Manage - user groups",
"access_policy" : "ROOT"
},
{
"_id" : 4,
"info" : "Manage users for DX-Client application",
"sub_section" : "Create - user",
"access_policy" : "ADMINISTRATOR"
},
],
"access_policy" : "ADMINISTRATOR"
}
meteor.html
<table class="table table-bordered">
<tbody>
{{#each temp_admin_section}}
{{#if admin_section}}
<tr class="bgLight">
<td class="left" id="one"><b>{{ section_id }}</b></td>
<td class="left" id="two"><b>RESTRICTED</b> - <code contenteditable="true" class="edited"><input value="{{ access_policy }}" /></code><a class="add-access pull-right">add</a></td>
</tr>
{{#each admin_section}}
<tr>
<td class="left" id="one">{{ sub_section }}</td>
<td class="left" id="two">RESTRICTED - <code contenteditable="true" class="edited">
<input value="{{ access_policy }}" /></code></td>
</tr>
{{/each}}
{{/if}}
{{/each}}
</tbody>
</table>
meteor.js
'change .edited': function(event, template){
var to = event.target.value;
var list = to.split(",");
map.update(
{"_id": this._id, "admin_section._id" : 1},
{$set: {"admin_section.$.access_policy": list}}
);
}
All client-side code is considered untrusted unless you call a Meteor.call and let a server-side method do the update. If you look in the console, you will probably see an error like this:
{
error: 403,
reason: "Not permitted. Untrusted code may only update documents by ID.",
details: undefined, message: "Not permitted. Untrusted code may only update documents by ID. [403]",
errorType: "Meteor.Error"
}
On the client-side, you can only update 1 document at a time, and you must choose the document to update by ID, so the 1st argument needs to be a mongo document ID, not a mongo selector:
MyCollection.update(
this._id,
{
$set: { "admin_section.1.access_policy": "TEST" }
}
)
Also, to update a sub-document of an array, rather than specifying the ID in the 1st argument as a selector, notice how I am specifying the ID inside the $set statement.
If you want to update all elements in the array, you have to loop through all of them individually:
var doc = MyCollection.findOne(this._id);
var adminSections = doc.admin_section;
for (i = 0; i < adminSections.length; i++) {
// If you need to access a value in the nested doc:
var nestedDoc = adminSections[i];
MyCollection.update(
this._id,
{
$set: { "admin_section." + (i+1) + ".access_policy": "someValue" }
}
);
{

trying to display json data with angularjs ng-repeat not working

I've seen so many ways to do this, but most are pretty old and I want to make sure I'm doing this correctly. Right now, the way I'm using isn't working and I feel like I'm missing something.
I'm getting the JSON back fine, I just need to get it to display in a table after I click the button.
Here is the JSON. This is how I'm going to get it from our server, I can't add any "var JSON =" or add any scope like "$scope.carrier" to the data, unless there's a way to add it after I've fetched the data.
{
"carrier":
[
{
"entity": "carrier",
"id": 1,
"parentEntity": "ORMS",
"value": "Medica"
}, {
"entity": "carrier",
"id": 2,
"parentEntity": "ORMS",
"value": "UHG"
}, {
"entity": "carrier",
"id": 3,
"parentEntity": "ORMS",
"value": "Optum"
}, {
"entity": "carrier",
"id": 4,
"parentEntity": "ORMS",
"value": "Insight"
}, {
"entity": "carrier",
"id": 5,
"parentEntity": "ORMS",
"value": "Insight"
}
]
}
Here is the app.js file to bring back the JSON data:
var app = angular.module('myTestApp', []);
app.controller('myController', ['$scope', '$http', function($scope, $http) {
var url = 'test.json';
$scope.clickButton = function() {
$http.get(url).success(function(data) {
console.log(data);
});
}
}]);
And then of course the HTML:
<div class="col-lg-12 text-center">
<button type=button class="btn btn-primary load" ng-click="clickButton()">Click!</button>
<table class="">
<tbody ng-repeat="carrier in carriers">
<tr>
<td>
<h3 class="">{{ module.entity }}</h3>
<h3 class="">{{ module.id }}</h3>
<h3 class="">{{ module.parentEntity }}</h3>
<h3 class="">{{ module.value }}</h3>
</td>
</tr>
</tbody>
</table>
</div>
I'm also wondering if I can use the ng-grid to put this in a table. I know they just upgraded it to ui grid so I'm not sure if this is still a feasible approach.
Also, I'm not getting errors, the data just won't display in the table right now. All I know is its returning the data properly, just not displaying in the table.
Any help is appreciated.
I looked at your plunker seems like you need to:
add angular script
wire the app and the controller
your variable in the repeater is wrong, I change it
take a look to this fixed plunker:
http://plnkr.co/edit/TAjnUCMOBxQTC6lNJL8j?p=preview
$scope.clickButton = function() {
$http.get(url).success(function(returnValue) {
alert(JSON.stringify(returnValue.carrier));
$scope.carriers = returnValue.carrier;
});
}
You never assign the value of the returned array to $scope.carriers.
At the line where you say console.log(data); add this:
$scope.carriers = data.data;
Here is the updated clickButton function (with a variable name change to reduce confusion):
$scope.clickButton = function() {
$http.get(url).success(function(returnValue) {
$scope.carriers = returnValue.data;
});
};

Data Table with Angularjs

I am using angularjs with MVC5 (.net) for creating single page website. I have problem to bind data with "data table(jquery)"
When first time bind data in to table at that time it's work fine but when i edit the record and rebind the data with data table at that time getting issue.
my code like bellow:
HTML
<table id="dt_Tarnsaction_Lunch" class="notinit">
<thead>
<tr>
<th >Employee Id</th>
<th >Edit</th>
</tr>
</thead>
<tbody id="TLunch">
<tr ng-repeat="TableRow in DashTranTableRows}" on-finish-tranlunch>
<td>{{TableRow.trancol_emplid}}</td>
<td >
<button ng-click="EditRecord(TableRow.trancol_dailytranspk)">
Edit
</button>
</td>
</tr>
</tbody>
</table>
"on-finish-tranlunch" Directive Code
appRoot.directive('onFinishTranlunch', function ($timeout) {
return {
restrict: 'A',
link: function (scope, element, attr) {
if (scope.$last === true) {
$timeout(function () {
scope.$emit('ngRepeatTranlunchFinished');
});
}
}
}
});
My Code In Controller
$scope.LoadData();
var OTransLunchTable;
$scope.$on('ngRepeatTranlunchFinished', function (ngRepeatTranlunchFinishedEvent)
{
if (!null)
{
if ($("#dt_Tarnsaction_Lunch").hasClass("init"))
{
OTransLunchTable.fnDraw();
}
else
{
$("#dt_Tarnsaction_Lunch").removeClass("notinit");
$("#dt_Tarnsaction_Lunch").addClass("init");
OTransLunchTable = $('#dt_Tarnsaction_Lunch').dataTable({
"sPaginationType": "bootstrap",
"sDom": "R<'dt-top-row'Clf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row'<'col-sm-6'i><'col-sm-6 text-right'p>>",
"fnInitComplete": function (oSettings, json) {
$('.ColVis_Button').addClass('btn btn-default btn-sm').html('Columns <i class="icon-arrow-down"></i>');
}
});
}
$('#dt_Tarnsaction_Lunch').width('100%');
}
else
{
$(".loading").hide();
alert("Error - Data can not be load");
}
});
My Code In Controller for load data first time as well as after edit record(both time i am using same method)
$scope.LoadData = function ()
{
myResource.getDashTableRows().then(function (d)
{
$scope.DashTranTableRows = d.data;
},
function (error) {
$(".loading").hide();
window.location = "login";
});
}
So, finally data loaded first time well and data table works fine at the first time but When i am edit record and load updated data at that time data table not loaded with updated data and also edit button not works.. :(
My JSON Format like bellow
[
{
"trancol_emplid": "a1",
"trancol_dailytranspk": 1
},
{
"trancol_emplid": "a2",
"trancol_dailytranspk": 2
},
{
"trancol_emplid": "a3",
"trancol_dailytranspk": 3
},
{
"trancol_emplid": "a4",
"trancol_dailytranspk": 4
},
{
"trancol_emplid": "a5",
"trancol_dailytranspk": 5
},
{
"trancol_emplid": "a6",
"trancol_dailytranspk": 6
}
]
My Service factory for load data from Server
angular.module('GratSyncSite').factory('myResource', function ($http)
{
var myResource =
{
getDashTableRows: function ()
{
$(".loading").show();
var promise = $http.get(WEBRESOURCEURL).success(function (response)
{
return response;
});
return promise;
}
}
});
Where are you posting your data? Is data even being received on server side?
On thing to note: MVC is not the best framework for SPAs. I would use ASP.NET WEB API (2.1) for server side.
That way API can be reused by 3rd party if you ever consider to open it to public.

Categories