How to get id from list of object using AngularJS? - javascript

I have api call on $on i got the Json response that is attached with the question. i was able to display fileName in the li , Now i have delete function when user click on remove icon i am calling function and trying to get rskAsesAprvAtchKy key so i can post the key to backend to delete this file.
It is coming undefined i am not sure what i am missing any help will be appreciated..
main.html
<div class="row">
<div class="col-md-6">
<ul>
<li ng - repeat="file in attachedDoc">{{file . fileName}}
<a href="" ng - click="deleteFile()">
<span class="glyph_remove"></span>
</a>
</li>
</ul>
</div>
</div>
factory.js
$scope.$on('addEditAttest', function (s, attestorObj) {
$scope.attestorObj = attestorObj;
attestorFactory.getAttachedDocument($scope.attestorObj.riskAssessmentRoleAsgnKey)
.then(function (response) {
$scope.attachedDoc = response.data;
});
});
$scope.deleteFile = function () {
var fileKey;
$scope.attachedDoc.rskAsesAprvAtchKy = fileKey;
console.log("deleted", fileKey);
}
JSON.JS
[{
"rskAsesAprvAtchKy": 1001,
"fileName": "Doc 1",
"rskAsesRoleAsgnKy": 1277
}]

You can pass the key as parameter for the ng-click method:
At the view
<li ng-repeat="file in attachedDoc">{{file.fileName}}
<a href="" ng-click="deleteFile(file.rskAsesAprvAtchKy, $index)"> //Key from the file
<span class="glyph_remove">
</span>
</a>
</li>
Change the delete method
$scope.deleteFile = function(fileKey, fileIndex){
/*Delete the file*/
$scope.attachedDoc.splice(fileIndex, 1); //remove the file at position fileIndex
}
EDIT:
Passing the $index from the ng-repeat and using Array.splice() will do the job. See above.

Related

Pass Ng Repeat value to ng click

I cant pass a value to form the ng-repeat to the ng-click in my angular aplication.
This is my html
<div ng-repeat="x in tt" >
<div>
<div ng-hide={{x.quien!=dameLocal.nombre}}>
<a href ng-click="edit(x.id)">
<i class='fa fa-pencil-square-o fa-2x ' ></i>
</a>
</div>
</div>
</div>
But the edit(x.id) dont recive any value.
inspecting the code, i get this:
<a href="" ng-click="edit(x.id)">
so, why i dont get the id value in the ng-click?
Thanks in advance
Edit:
If i put for example a
data-id={{x.id}}
it get the x.id value, so what gives?
edit2:
Here is my Js:
$scope.edit=function(a){
console.log(a);
// $scope.comentEdit(a);
// $scope.comentDel(a);
}
This id will send to your function edit(). Put a breakPoint in dev tools in edit function and you will see this id in it.
$scope.edit = function(id) {
console.log(id);
};
Your data tt should be like this in that case:
$scope.tt = [
{
id: "123",
name: "item"
}
];

AngularJs filter not updating view

The view in my html is not getting filtered on selecting any li element.
But when I console the filter functions the output generated is correct.Also how to clear the filter so it is reusable again.I'm getting a blank page on clicking open or close select elements.Can anyone help me with this.
I have used two filters in a controller inside the functions like this-
indexController Functions-
this.UserTickets = ()=> {
//code to get the tickets
}
this.openTickets = () => {
index.filteredTickets = $filter('filter')(index.tickets, { status: "open" } );
console.log(index.filteredTickets);
};
//filter closed tickets
this.closeTickets = () => {
index.filteredTickets = $filter('filter')(index.tickets, { status: "close" } );
console.log(index.filteredTickets);
};
this.clearFilter = () => {
//clear the filter
};
HTML-
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a ng-click="indexCtrl.clearfilter()">None</a></li>
<li><a ng-click="indexCtrl.openTickets()">Open</a></li>
<li><a ng-click="indexCtrl.closeTickets()">Close</a></li>
</ul>
<div ng-repeat="ticket in indexCtrl.tickets | filter:tickets |filter:indexCtrl.filteredTickets">
<div class="ticket-no">
<h4>Ticket No:<span>{{ticket}}</span></h4>
</div>
<div class="ticket-title">
<a ng-href="/ticketView/{{ticket.ticketid}}"><h3>{{ticket.title}}</h3></a>
</div>
<div class="ticket-info">
<p class="pull-left">{{ticket.username}} On {{ticket.created | date:"MMM d, y h:mm a"}}</p>
<p class="pull-right">Status:<span>{{ticket.status}}</span></p>
</div>
<hr class="hr">
</div>
You are mixing both angular filter options. I would recommend the javascript filters, index.filteredTickets=$filter('filter')(index.tickets,{status:"open"}); rather than the html template syntax, ng-repeat="ticket in indexCtrl.tickets | filter:tickets...". The key difference between these methods is how often they are run. The html template syntax filters are run on every digest cycle, the javascript filters are only run when the method is called, in your case, on each button click. For small apps or when the lists are small, this difference won't be noticeable, but if your app grows in size, the constant filtering on each digest cycle can cause page lag.
The filters in the controller are my preferred way of handling this, so I will show you how to clean up your code for these to work. You are almost there, just a few small changes are needed.
In your html, you can remove the inline filters in the ng-repeat, these aren't needed, and change the array to be your filter list, index.filteredTickets.
.html
<ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a ng-click="indexCtrl.clearfilter()">None</a></li>
<li><a ng-click="indexCtrl.openTickets()">Open</a></li>
<li><a ng-click="indexCtrl.closeTickets()">Close</a></li>
</ul>
<div ng-repeat="ticket in indexCtrl.filteredTickets">
<div class="ticket-no">
<h4>Ticket No:<span>{{ticket}}</span></h4>
</div>
<div class="ticket-title">
<a ng-href="/ticketView/{{ticket.ticketid}}"><h3>{{ticket.title}}</h3></a>
</div>
<div class="ticket-info">
<p class="pull-left">{{ticket.username}} On {{ticket.created | date:"MMM d, y h:mm a"}}</p>
<p class="pull-right">Status:<span>{{ticket.status}}</span></p>
</div>
<hr class="hr">
</div>
For the javascript, you need to make sure the filteredTickets are accessible in the html. I'm not sure if index == this, if not, you may need to attach the filtered tickets to the scope. The one other change needed is to set the filteredTickets to your original list if the none button is pressed. You will also want to call clearFilter after you load the list, otherwise index.filteredList will be undefined/null.
.js
this.UserTickets = () => {
//code to get the tickets
....
//after getting list, call clear filter
this.clearFilter();
}
this.openTickets = () => {
index.filteredTickets = $filter('filter')(index.tickets, { status: "open" } );
console.log(index.filteredTickets);
};
//filter closed tickets
this.closeTickets = () => {
index.filteredTickets = $filter('filter')(index.tickets, { status: "close" } );
console.log(index.filteredTickets);
};
this.clearFilter = () => {
//clear the filter
index.filteredTickets = index.tickets;
};

Angular Display lists from Firebase

My data in Firebase looks like this...
evalu8er
situations
-K6rM12D-0nt4fJH_QcA
situation: "Test"
-K6rPoHiUl2N2JOSWXww
situation: "Test2"
-K6rPqbkBHJ-K8znVzay
situation: "Test3"
I have inserted the data from an HTML page via a form like this...
<div class="form-group">
<label for="situation">Add a situation</label>
<input type="text" class="form-control" id="situation" placeholder="Situation" ng-model="situation">
</div>
<button type="submit" class="btn btn-default pull-right" ng-click="add_situation()"><i class="fa fa-cog fa-spin" ng-show="loading"></i> Add </button>
</form>
The above form is calling the controller...
app.controller("situations", ["$scope", function ($scope) {
$scope.add_situation = function () {
var situation = $scope.situation;
var ref = new Firebase("https://evalu8er.firebaseio.com/situations");
ref.push().set({
situation: situation
});
};
}
]);
Now I want to get each of the situations back to the page, and this where it all goes wrong for me.
Inside the same controller as above I'm adding this....
var ref = new Firebase("https://evalu8er.firebaseio.com/user/situations/");
ref.on("value", function(snapshot) {
$scope.display_situatoins = snapshot.val();
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
And on the HTML page I have added
<li data-ng-repeat="x in display_situatoins">
{{ x }}
</li>
When the page loads it DOES NOT show me the data until I enter something in the form field,
Question 1/3)
How do I get the data to show on page load?
When it does load it looks like this...
{"situation":"Test"}
{"situation":"Test2"}
{"situation":"Test3"}
And what I want is just to show a list of the situations like this..
Test
Test2
Test3
Question 2/3)
How do I just show the situation values as above?
And when I do add a new item it gets listed at the bottom, how do I order the list with the new items at the top?
Question 3/3)
How do I order the list so the new items appear first?
Use AngularFire for synchronized collections.
angular.module('app', ['firebase'])
.constant('FirebaseUrl', '<my-firebase-app>')
.service('rootRef', ['FirebaseUrl', Firebase])
.controller('MyCtrl', MyController);
function MyCtrl($scope, rootRef, $firebaseArray) {
$scope.situations = $firebaseArray(rootRef.child('situations');
}
Then in your template for MyCtrl, you can do an ng-repeat on the situations array.
<li ng-repeat="situation in situations">
{{ situation.situation }}
</li>
The {{ situation.situation }} part looks awkward because of the naming. If you change the property situation to something like text or title it would look like:
<li ng-repeat="situation in situations">
{{ situation.title }}
</li>

ng-repeat with ng-switch: Need to call service in anchor. How?

I have a SPA set up with some complex code. First, i am making a call to a service to get some data and binding it to a scope object. Code example below:
$scope.tables.outgoingCommunication = {
columns: OutgoingCommunicationModel.columns,
rows: []
};
$scope.getOutgoingDocs = () => {
myService.GetPrintHistory($scope.item.ItemId, $scope.item.ItemDesc, $scope.oDocAge).success((response) => {
$scope.tables.outgoingCommunication.rows = response.Response.body.Value;
});
};
My HTML has this code to bind to the outgoingCommunication table:
<section ng-if="tables.outgoingCommunication.rows.length" table-directive="outgoingCommunication" rows="tables.outgoingCommunication.rows" columns="tables.outgoingCommunication.columns" sort-field="'DatePosted'" descending="true" parent-method="toggleAge()" table-template="Templates/app/items/Outgoing-Communication.html"></section>
The template has this code in it:
<div id="outgoing-communication" class="table-responsive">
<div class="table container-fluid overflow-scroll" >
<!--Header Row-->
<div class="thead row tr hidden-xs">
<div ng-repeat="column in columns" class="{{column.columnSize}} th" ng-class="{'overflow-ellipsis': column.allowTruncate == true}" ng-click="column.sortable && Sort(column.field)">
{{column.title}} <i ng-if="column.sortable == true" ng-class="{'icon icon-caret-down inactive': sortField != column.field, 'icon icon-caret-down': descending && sortField == column.field, 'icon icon-caret-up': !descending && sortField == column.field}"></i>
</div>
</div>
<!--Body Rows-->
<div ng-repeat="row in rows | orderBy:sortField:descending" class="row tr">
<div>
<!--Switch Case-->
<div ng-switch="column.field" ng-repeat="column in columns" class="{{column.columnSize}} td" ng-class="{'overflow-ellipsis': column.allowTruncate == true}">
<b class="visible-xs-inline-block">{{column.title}} </b>
<!--When Actions-->
<div ng-switch-when="Actions">
View <i class="icon icon-lg icon-file-o"></i>
</div>
<!--When DatePosted-->
<div ng-switch-when="DatePosted">
{{row[column.field] | date: 'MM/dd/yyyy'}}
</div>
<!--When Default-->
<div ng-switch-default>{{row[column.field]}}</div>
</div>
</div>
</div>
</div>
<a ng-if="$parent.oDocAge == 1" href="" ng-click="parentMethod()">View More</a>
<a ng-if="$parent.oDocAge == 3" href="" ng-click="parentMethod()">View Less</a>
</div>
The data I am getting back from the call to GetPrintHistory has a JSON format as follows:
{
FormNumber: "1060",
FormDescription: "Invoice",
PrintProcessId: 6440187,
DatePosted: "2014-12-20T00:00:00",
PrintXMLId: 5286992,
ItemImageNum: 26
}
There is a series of these items in the collection.
My model is defined as:
define(["require", "exports"], function (require, exports) {
var OutgoingCommunicationModel;
(function (OutgoingCommunicationModel) {
OutgoingCommunicationModel.columns = function () {
return [
{
field: "DatePosted",
title: "Date Posted",
columnSize: "col-sm-3",
allowTruncate: true,
sortable: true
},
{
field: "FormDescription",
title: "Description",
columnSize: "col-sm-3",
allowTruncate: false,
sortable: true
},
{
field: "Actions",
columnSize: "col-sm-3",
allowTruncate: false,
sortable: false
}
];
};
})(OutgoingCommunicationModel|| (OutgoingCommunicationModel= {}));
return OutgoingCommunicationModel;
});
My current code is displaying the FormDescription column and DatePosted field with no problem. The problem is the Actions column. I need to have the anchor call a service method defined below:
this.GetOutgoingDocument = function (itemId, itemImageNumber, printProcessId, printXmlId) {
return _this.$http({
method: "GET",
url: "api/item/GetOutgoingDocument",
params: { itemId: itemId, itemImageNumber: itemImageNumber, printProcessId: printProcessId, printXmlId: printXmlId }
});
};
I cannot for the life of me figure out how to set up the call in the ng-repeat with the ng-switch-when embedding to call the service method. If I need to, I can try and build a codepen or something to get a sample set up.
Have you tried ng-init?
<div ng-switch-when="Actions">
View <i class="icon icon-lg icon-file-o"></i>
</div>
This could work if you want the service called when switching, if you want the service called when clicking a button you could use ng-click = "GetOutgoingDocument()"
This is assuming you have GetOutgoingDocument on the $scope.
So there were a few ways I needed to face this.
The table directive I was using to open the template and display the data had an isolated scope. To get around this, I added a scope variable externalCall: "&" and set up my section tag that called this directive as follows: external-call="selectRow(itemId,itemImageNum, printProcessId, printXMLId)". Finally, I used this in my anchor code: <a ng-click="externalCall({itemId: row.ItemId, itemImageNum: row.ItemImageNum, printProcessId: row.PrintProcessId, printXMLId: row.PrintXMLId})">View <i class="icon icon-lg icon-file-o"></i> </a>
As you can see in the code above, I discovered the row variable held all the data i needed from my row that was returned.
In the long run, I ended up having to take a slightly different route. Since I am returning a PDF from the Web API call, I instead moved over to ng-href to call the API call directly.
<a target="_blank" ng-href="api/policy/GetOutgoingDocument?itemId={{row.ItemId}}&itemImageNum={{row.ItemImageNum}}&printProcessId={{row.PrintProcessId}}&printXMLId={{row.PrintXMLId}}">View <i class="icon icon-lg icon-file-o"></i> </a>
I will need to do something about the Web API call though. If I get an error, I am seeing an Ajax document showing a 400 error on it. I want to handle it differently than that. May have to ask a different question.

My Virgin Parse.Query

I've been attempting to make my virgin query with JavaScript from a Parse database. I'd like to take data from a Parse column (named primary) and display it on the front end on a drop down. I've tried a large number of combinations but as of now I'm unable to make much progress. My Angular controller:
angular.module('startupApp')
.controller('bizOfferCtrl', function ($scope, $http) {
var primary = new Parse.Query(bizCategories);
$scope.getPrimary = function() {
$scope.bizCategories.relation("primary").query().find({
success: function(list) {
$scope.bizCategories.primary = list;
}
});
};
And the html (with bootstrap and SCSS) that goes along with that:
<div class="btn-group col-xs-4 col-sm-4 col-md-4 col col-lg-4" dropdown is-open="status.isopen">
<button type="button" class="btn btn-primary" dropdown-toggle>
{{getPrimary()}} <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" >
<li ng-repeat="category in bizCategories.primary">
{{category.primary}}
</li>
</ul>
</div>
You're not providing an error callback for the query, which could be used to provide insight into why your query is failing. See here.
You're also calling query().find() but you defined and bound the query to primary and Parse.Query is not a function, but an object. Try
primary.find({
success: function(list) {
$scope.bizCategories.primary = list;
}, error: function(error) {
// handle error
}
});
Also, I don't know if chaining the function call in the way you did is valid either, but I don't use Angular JS so I can't speak to the validity of this. From my perspective, it looks like you're trying to access it as a property of all of that.

Categories

Resources