angularjs remove from array without knowing index - angularjs

I have an arraylist which is used to display a leave request workflow. If a vacation leave request is currently saved as a draft, the request is added to my draft list, however if it's been submitted from a modal form to be approved it would need to be removed from the draft list and added to the approval list. My question is the list are external to my form and my form has does not know the index of the list. When I update my request from draft to approve, how do I remove it from the draft list and add it to the approved list without knowing the index.
The first thought that came to mind was to create a unique attribute with the objects database pk like so data-approval="7"and select it with some sort of jquery function and remove the item from the list, but from what I read, that isn't the angular way to do things. So without knowing the index how would I remove an item from my list in angularjs?
Example of loop.
<ul>
<li ng-repeat="e in pendingApprovals" data-approval="{{e.id}}">
<div class="alert alert-info">
<h5>{{e.title}}</h5>
<div>
{{e.type}}
</div>
{{e.start | date:'MM/dd/yyyy - hh:mm a'}}
{{e.end | date:'MM/dd/yyyy - hh:mm a'}}
<a ng-click="rejectClick(e.id)" class="btn btn-danger btn-xs btn-block">
<i class="fa fa-thumbs-down fa-1"></i>
Reject
</a>
<a ng-click="approveClick($index, e.id)" class="btn btn-success btn-xs btn-block">
<i class="fa fa-thumbs-up fa-1"></i>
Approve
</a>
</div>
</li>
</ul>
JS
modalInstance.result.then(function(formData) {
$http.post('./calendar/save.json', formData).then(
function(response) {
if(formData.update) {
$scope.refresh();
console.log('refresh')
angular.element(elem[0].querySelector('[data-unsubmitted="' + response.data.id + '"]')).remove();
} else {
$scope.events.push(response.data);
$scope.pendingApprovals.push(response.data);
}
}, function(response) {
console.log('failure ' + response)
// called asynchronously if an error
// occurs
// or server returns response with an
// error status.
});
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});

It appears as if filters as #ste2425 was in fact the solution.
modalInstance.result.then(function(formData) {
$http.post('./calendar/save.json', formData).then(
function(response) {
if(formData.update) {
$scope.refresh();
var items = $scope.pendingApprovals;
var item = $filter('filter')(items, {id: response.data.id}, true)[0];
var index = items.indexOf(item);
$scope.pendingApprovals.splice(index,1);
} else {
$scope.events.push(response.data);
$scope.pendingApprovals.push(response.data);
}
}, function(response) {
console.log('failure ' + response)
// called asynchronously if an error
// occurs
// or server returns response with an
// error status.
});
}, function() {
$log.info('Modal dismissed at: ' + new Date());
});
I also found help from this SO question how to get index position of an array item in controller passing a value in angularjs

Related

Click event not defined via jquery

I have got the following DataTable with data and web bootstrap links displayed via the appropriate columns as shown below:
$(document).ready(function() {
$('#example').DataTable({
destroy: true,
"ajax":{
"url":"http://localhost:3000/tasks/list",
"dataSrc": ""
},
"columns":[
{"data":"title", "title":"Τίτλος"},
{"data":"description", "title":"Περιγραφή"},
{ "data": "ID",
"title": "Επισκόπηση",
"render": function(data, type, row, meta){
if(type === 'display'){
data = '<a class="btn btn-success btn-sm viewlink" role="button" data-toggle="modal" data-target="#viewModal" href="/tasks/todo/' + data + '">' + '<i class="fas fa-eye"></i>' + '</a>';
}
return data;
}
} ],
length: 20,
});
$('.viewlink').on("click", function(e){
console.log("Hello!!!");
});
});
Unfortunately when i press the bootstrap link button, i do not get any response via console.log.
Any idea that would be convenient to me!
Regards
You must use a delegated event handler, i.e
$('#example').on('click', '.viewlink', function(e) {
//
})
Reason: At the time your handler is declared no .viewLink's are present in DOM.

how to Dynamically Active tab with content for ui bootstrap tabs in angularjs?

I want to dynamically active tab with content in angular js
my code is
<uib-tabset ng-if="pets_count > 0" class="petsTabs tab-animation">
<div ng-repeat="(key, pet) in pets_list">
<uib-tab heading="{{pet.pet_name}}" active="{{pet.pet_id == activePet}}">
<div class="petsTabsContent" >
<h4>
{{pet.pet_name}}
<small>
Boarding Dates: {{ pet.start_date | date : 'MMMM d, y'}} to {{ pet.end_date | date : 'MMMM d, y'}}
</small>
</h4>
</div>
</uib-tab>
</div>
</uib-tabset>
i have two variables pet.pet_id, activePet on base for these variables i have to active tab.
but it does not working i am new to angular js
thanks in advance
This controller
$scope.show_pet_function = function () {
var pet_id;
var action;
pet_id = parseInt($('.pet_view_option').attr('data-pet_id'));
action = $('.pet_view_option').attr('data-action');
petowner_user_id = parseInt($('.pet_view_option').attr('data-pet-owner'));
var details = $scope.hidePetData;
$http.post(CONFIG.APIURL + 'Pets/changePetHideStatus/', {pet_id: pet_id, action: action})
.then(function (response) {
if (response.data.action == 'show_pet') {
promise = petlistFunction(petowner_user_id).then(function (response) {
$scope.activePet = pet_id;
angular.extend($scope.pets_list, response.data['pets_list']);
});
toastr.success(response.data.message);
} else if (response.data.action == 'hide_pet') {
promise = petlistFunction(petowner_user_id).then(function (response) {
$scope.activePet = pet_id;
angular.extend($scope.pets_list, response.data['pets_list']);
});
}
});
}
This is response for pet_list object type array
I think there might be an issue with $scope binding, as you are pulling the data in then-able function.
So try by placing $scope.$apply() after the $http response.
For reference add it like this
angular.extend($scope.pets_list, response.data['pets_list']);
$scope.$apply();

Getting variables from an array in MVC 4 and sending to controller via jQuery ajax

I'm iterating through an array in my MVC 4 view using a foreach:
#model dynamic
#foreach (var item in Model)
{
<tr class="row">
<td>#Html.Label("", (string)item.DisplayName)</td>
<td><span class="glyphicon glyphicon-folder-open" id="btnOpen" data-edit-id="OpenDocument" title="#Text.Get(Text.eTextType.Button, "Open")"></span></td>
</tr>
}
As you can see above I'm sending my variables across in the url. I really don't want to do this so I have this function:
function SendToFilter() {
$.ajax({
url: "#Url.Action("ReportListing", "Reporting", null)",
type: "POST",
data: { 'UReportFileName': UReportFileName },
success: function (result) {
// Send the user to correction action method of controller
var link = '#Url.Action("ReportListing", "Reporting", null)';
window.location.href = link;
}
});
};
Id rather use:
<td><span class="glyphicon glyphicon-folder-open" id="btnOpen" data-edit-id="OpenDocument" title="#Text.Get(Text.eTextType.Button, "Open")"></span></td>
and send the variables behind the scenes with an ajax post request, but ReportItemId and MimeType come from the controller and I get them in the foreach loop. How can I best access these variables from the javascript function? I really didn't want to attach the variables to the link tag. Is this something that is possible?
As long as you build the correct href value for your link in your razor markup, you can use the same value when making the ajax call.
Add a css class to the anchor tags so that we can use it later for our jQuery selection.
<td>
<a class="ajaxLink"
href="#Url.Action(item.ViewName, "Reporting", new { #name = "SendToFilter",
ReportItemId = item.ReportItemId, MimeType = item.MimeType })"
alt="A Link">
<span class="glyphicon glyphicon-folder-open" data-edit-id="OpenDocument"
title="#Text.Get(Text.eTextType.Button, "Open")"></span>
</a>
</td>
And in your javascript, listen to the click event on anchor tag with the css class ajaxLink
$(function(){
$("a.ajaxLink").click(function(e){
e.preventDefault(); // prevent the default click behaviour
$.post($(this).attr("href"),function(response){
//do something with the response
// reload to some other page
// window.location.href="#Url.Action("ReportListing","Report")";
});
});
});
If you do not wish to keep the items in the href value for any reasons, you may keep those in html 5 data attributes of the anchor tag and read them in the click event and append it to the url before making the $.post call.
<td>
<a class="ajaxLink"
href="#Url.Action(item.ViewName, "Reporting")"
data-name="SendToFilter" data-reportitemid="#item.ReportItemId"
data-mime="#item.MimeType"
alt="A Link"> Link Text </a>
</td>
And in the click event,read the data attributes and append to the url
$(function(){
$("a.ajaxLink").click(function(e){
e.preventDefault(); // prevent the default click behaviour
var _this=$(this);
var myUrl=_this.attr("href");
myUrl+="?name="+_this.data("name");
myUrl+="&reportItemId="+_this.data("reportitemid");
myUrl+="&MimeType="+_this.data("mime");
alert(myUrl);
$.post(myUrl,function(response){
//do something with the response
// reload to some other page
// window.location.href="#Url.Action("ReportListing","Report")";
});
});
});

How to get value in another controller - Angular JS

I am creating some divs using ng-repeat.
See code below :
.controller('meditationsController', function ($scope, $state, $rootScope, $http) {
var req = {
method: 'POST',
url: 'http://example.com/demo/',
headers: {
'Content-Type': 'application/json'
}
}
// Call API
$http(req).then(function(result) {
var rawData = result.data;
$scope.meditationByCategory = {};
for (var i = 0; i < rawData.length; i++) {
var meditation = rawData[i];
if ($scope.meditationByCategory[meditation.main_title] == undefined) {
$scope.meditationByCategory[meditation.main_title] = {};
$scope.meditationByCategory[meditation.main_title].name = meditation.main_title;
$scope.meditationByCategory[meditation.main_title].meditations = [];
}
$scope.meditationByCategory[meditation.main_title].meditations.push(meditation);
}
});
})
<div ng-repeat="(categoryName, category) in meditationByCategory">
<div class="peacefulness"><p class="para-text">{{category.name}}</p></div>
<a href="" ng-click="goToDetailPage()" class="customlink">
<div class="item-content" ng-repeat="meditation in category.meditations">
<span class="leftSpanStyle">{{meditation.title}}</span>
<span class="rightSpanStyle">
<i class="icon ion-ios-information-outline icon-size"></i>
</span>
</div>
</a>
</div>
I have successfully created the list of divs dynamically according to service response.
Now i want to apply click to each div. and the data that i am getting in service response want to bind the next page. I mean the data on the next page will be dynamic and depend upon cliked div.
please help me to bind the data into another page..
Add a button to your view. Something like:
<span class="rightSpanStyle">
<i class="icon ion-ios-information-outline icon-size"></i>
</span>
<button ng-click="doSomeThing($index)"></button>
And in your controller:
$scope.doSomeThing = function(index){
//do something with category.meditations[index]
//or go to another state: $state.go("myState", {item: category.meditations[index]})
}
Edit:
As you say "want to bind to next page" I assume that you want to navigate to another page. Assuming also that you do so by using angulars ui-router, that means that you want to change state. In that case don't forget to define:
url: /myUrl/:item
for that state in question. You can access the item in the target state / controller with $stateParams.item

How to show value on ng-click event?

I am bit new to AngularJs and looking for help on some basic concepts.
Basically the following code correctly shows data returned from request API.
Request.cshtml
<div data-ng-controller="PostsController">
<strong class="error">{{ error }}</strong>
<strong data-ng-show="loading">loading..</strong>
<div data-ng-repeat="request in posts | orderBy: 'Id':true">
<strong>ID: {{ request.Id }}</strong>
<strong>Contact No: {{ request.ContactNumber }}</strong>
</div>
</div>
now i am further looking to add button in view and when user click on in, the contact number should be displayed.
i have written following html/angular view code.
show number
I need help in writing the corresponding "ShowNumber()" function in PostsController.js file.
But i am confused how to send single value instead of lists. Any help on it please?
here is my current PostsController.js code
function PostsController($scope, $http) {
$scope.loading = true;
$scope.editMode = false;
$http.get('/api/request').success(function (data) {
$scope.posts = data;
$scope.loading = false;
})
.error(function () {
$scope.error = "An Error has occured while loading posts!";
$scope.loading = false;
});
}
The function:
$scope.ShowNumber=function(value){
//Your logic
}
HTML
<input type="button" value="Show" ng-click="ShowNumber(request.Id)" />
You can send any value in the function.
Also you can send a index of list:
ng-click="ShowNumber($index)"

Resources