I'm changing a model and I was expecting the view to update but it isn't:
Here is my view:
<div ng-controller="showCarCtrl">
<h1>Damaged Cars</h1>
<table border="1">
<tr>
<th>Plate Number</th>
<th>Brand</th>
<th>Color</th>
</tr>
<tr ng-repeat="car in cars" ng-show="car.damaged">
<td>{{car.plate_number}}</td>
<td>{{car.brand}}</td>
<td>{{car.color}}</td>
<td>
<button ng-click="setRepaired(car.cid)">Repaired</button>
</td>
</tr>
</table>
</div>
Here is the controller:
app.controller('showCarCtrl', function($scope, $rootScope,CarService){
$scope.setDamaged = function(cid){
console.log("setting the car as damaged "+cid)
$rootScope.loading = true;
CarService.setDamageCar(cid)
.then(function(data){
$rootScope.loading = false;
console.log("set damage 1")
for(var i=0; i<$scope.cars.length; i++) {
console.log("setting car as damage");
if ($scope.cars[i]==cid) {
$scope.cars[i].damaged = 1
$scope.$apply();
console.log("it enters here");
break;
}
console.log($scope.cars)
}
},
//deferred
function(data){
console.log('Car Service failed');
$rootScope.loading = false;
});
};
});
I've checked from the server, the reply from the server is properly comming and I'm successfully updating the model at $scope.cars[i].damaged = 1, the only issue is that I was expecting the view to change because as shown above, in the view, I've something as <tr ng-repeat="car in cars" ng-show="car.damaged">, but the view is not updating
I think you have an error in your code here:
if ($scope.cars[i]==cid) {
Maybe it should be like this:
if ($scope.cars[i].cid === cid) {
Related
For each make and model added via the "add" button, I need to check for a duplicate, set an alert if there is a duplicate and not let it add to the table. Cannot seem to find the solution...
Below is the entire code for the beginner project I am working on. My apologies ahead of time for this post, it is my first here... Thanks all.
<div>
<div>Make: <input type="text" ng-model="make"></div>
<div>Model:<input type="text" ng-model="model"></div>
<button ng-click="add()">Add</button>
<tr>
<th>Make</th>
<th>Model</th>
</tr>
<tr ng-repeat="car in cars" ng-click="rowClick(car)">
<td>{{car.make}}</td>
<td>{{car.model}}</td>
</tr>
<table class="table carsTable">
<tr>
<th>Make</th>
<th>Model</th>
</tr>
<tr ng-repeat="car in cars" ng-click="rowClick(car)">
<td>{{car.make}}</td>
<td>{{car.model}}</td>
</tr>
<script>
var carsApp = angular.module('carsApp', []);
carsApp.controller('carController', function ($scope){
$scope.cars = [];
$scope.add = function () {
$scope.cars.push({
make: $scope.make,
model: $scope.model
});
$scope.make = null;
$scope.model = null;
};
$scope.rowClick = function(car){
$scope.make= car.make;
$scope.model= car.model;
};
$scope.alert = function(){
alert('Already exists in table');
}
});
You can check for duplicates by checking each car in your array (comparing the make and model) - you can accomplish this with Array.some (returns a boolean if any of the elements in the array match the condition):
In your add function:
var hasDuplicates = $scope.cars.some(car => car.make == $scope.make && car.model == $scope.model);
if (hasDuplicates) {
alert("Car already exists");
} else {
$scope.cars.push({
make: $scope.make,
model: $scope.model
});
}
If you can't use arrow syntax:
var hasDuplicates = $scope.cars.some(function(car) {
return car.make == $scope.make && car.model == $scope.model;
});
$scope.add = function () {
let dataToAdd = {
make: $scope.make,
model: $scope.model
};
let alreadyAdded = $scope.cars.some((o) => angular.equals(o, dataToAdd ));
if (alreadyAdded) {
$scope.alert();
return false;
}
$scope.cars.push(dataToAdd);
$scope.make = null;
$scope.model = null;
};
I am working on a Web Application using Laravel as backend API and AngularJS for frontend. I have successfully fetched the data from Laravel API and displayed it via AngularJS ng-repeat. Now i want a delete button for each record which is displayed in the table. When a user click that delete button it should delete the clicked record.
I did the following try which is working perfectly.But the problem occurs when i click delete button it deletes record from database but it is not refreshing the records list , instead of refreshing it just shows the headers titles of table and nothing else. When i manually refresh it from browser then it displays back the records list. I want to load the list automatically after the record is deleted.
Console Error : Console Error: DELETE
http://localhost/ngresulty/public/api/result/50?id=50 500 (Internal
Server Error)
Before Delete ( List ):
After delete Scene:
MainCtrl.js
$scope.deleteResult = function(id) {
$scope.loading = true;
Result.destroy(id)
.success(function(data) {
// if successful, we'll need to refresh the comment list
Result.get()
.success(function(data) {
$scope.students = data;
$scope.loading = false;
});
});
};
MyAppService.js
angular.module('myAppService', [])
.factory('Result', function($http) {
return {
get : function() {
return $http.get('api/result');
},
show : function(id) {
return $http.get('api/result/' + id);
},
save : function(resultData) {
return $http({
method: 'POST',
url: 'api/result',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(resultData)
});
},
destroy : function(id) {
return $http.delete('api/result/' + id,{params: {id}});
}
}
});
App.js
var myApp = angular.module('myApp', ['mainCtrl', 'myAppService']);
Results View :
<table class="table table-striped">
<thead>
<tr>
<th>Roll No</th>
<th>Student Name</th>
<th>Father Name</th>
<th>Obtained Marks</th>
<th>Total Marks</th>
<th>Percentage</th>
<th>Delete</th>
</tr>
</thead>
<tbody ng-hide="loading" ng-repeat="student in students | filter:searchText">
<tr>
<td>#{{ student.rollno }}</td>
<td>#{{ student.name }}</td>
<td>#{{ student.fname }}</td>
<td>#{{ student.obtainedmarks }}</td>
<td>#{{ student.totalmarks }}</td>
<td>#{{ student.percentage }}</td>
<td>
Delete</p>
</td>
</tr>
</tbody>
</table>
What I tried but not working :
$scope.deleteResult = function(id) {
$scope.loading = true;
Result.destroy(id)
.success(function(data) {
// do something with data if you want to
$scope.students.splice(id, 1);
});
};
Solution :
Whenever you get 500 internal error the issue will be from server side. The issue was with server side all i did was change my destroy service to
destroy : function(id) {
return $http.delete('api/result/' + id);
}
and in laravel controller i was returning a bool value true but i changed that to ID
return \Response::json($studentid);
because i was in need of that ID for success return and then it worked like a charm.
The problem is Array splice method takes the index of array as first argument and you are providing it Student Id which is not a array index. You have to find the index of student id in the array then pass it into the splice method
$scope.findWithAttr= function(array, attr, value) {
for(var i = 0; i < array.length; i += 1) {
if(array[i][attr] === value) {
return i;
}
} }
Now you can call this function is destroy success block.
$scope.deleteResult = function(idToDelete) {
$scope.loading = true;
$http.delete('api/result/' + id,{params: {id}}); }
.then(function(data) {
var index=$scope.findWithAttr($scope.students,id,idToDelete);
$scope.students.splice(index, 1);
});
};
You are splicing the data incorrectly.
Do like this to splice the data in destroy success block.
var del_index = $scope.students.findIndex(function(d){return d.id == id});
if(del_index>0)//if index of the id to be removed found
$scope.students.splice(del_index, 1);
There is a javascript library called lodash
This library provides the remove function where you can remove an element from the data.
Sometimes slice does not work. SO try this hopefully it would work.
$scope.deleteResult = function(id) {
$scope.loading = true;
Result.destroy(id)
.success(function(data) {
// do something with data if you want to
_.remove($scope.students,function(student){
return id==studednt.id;
}
});
};
New to Angular, I am trying to save a form and update the view after calling a PUT or POST call to the backend. Once I receive an OK status from the backend, I am updating my models with the latest response. But only the model in the directive "ng-click" gets updated but others do not. Here is my code:
///HTML
<table class="footable table table-stripped toggle-arrow-tiny" data-page-size="8">
<thead>
<tr>
<th data-toggle="all">Release Title</th>
<th data-hide="all">Release Genre</th>
<th data-hide="all">UID</th>
<th data-hide="all">Classical</th>
<th data-hide="all">Tracks</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="album in vm.albums" footable>
// This one (album.data.title) gets updated but the other ones do not
<td ng-click="vm.editAlbum(album, $index)">{{album.data.title}}</small></td>
<td>{{album.data.genre}}</td>
<td>{{album.data.uid}}</td>
<td ng-if!="album.data.classical">No</td>
<td ng-if="album.data.classical">Yes</td>
<td>
<li ng-repeat="track in album.data.tracks">
<a ng-click="vm.selectTrack(album, track)">{{track.title}}</a>
</li>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
<ul class="pagination pull-right"></ul>
</td>
</tr>
</tfoot>
</table>
Here is my controller:
// controller.js (Just pasting the saveRelease method that does the on-click event handling in HTML:
(function (){
angular.module('app.uploadedReleases').controller('UploadedReleasesController', UploadedReleasesController);
UploadedReleasesController.$inject = ['$http', '$log', '$scope', '$state', '$rootScope', 'APP_CONFIG'];
function UploadedReleasesController ($http, $log, $scope, $state, $rootScope, APP_CONFIG){
var vm = this;
vm.albums = []; // list of all albums
vm.albumPriority = [0, 4, 6, 8, 10];
vm.getAlbumTracks = getAlbumTracks;
vm.editAlbum = editAlbum;
vm.selectTrack = selectTrack;
vm.selected = {};
vm.saveRelease = saveRelease;
vm.testingAlbumSelected = false;
return init();
function init(){
$http.get('http://localhost:8080/api/releases').then(function(responseData){
//check the status from the response data.
vm.responseStatus = responseData.status;
if(vm.responseStatus !== 200){
//error message
}
// else, Parse the json data here and display it in the UI
for(var album in responseData.data){
vm.albums.push({slug: album, data: responseData.data[album]});
}
})
}
function getAlbumTracks(slug, index){
$http.get('http://localhost:8080/api/releases/' + slug).success(function(trackResponse){
//parse each album and get the track list
vm.showingAlbumIndex = index;
vm.albums.tracks = [];
vm.selected = {};
vm.selected.album = vm.albums[index];
vm.testingAlbumSelected = true;
for(var i = 0; i<trackResponse.tracks.length; i++) {
vm.albums.tracks.push(trackResponse.tracks[i]);
}
$log.debug(vm.albums.tracks);
vm.formAlbum = new Album(vm.selected.album.data.upc,
vm.selected.album.data.title,
vm.selected.album.data.label,
vm.selected.album.data.genre,
vm.selected.album.data.releaseType,
vm.selected.album.data.holdDate,
vm.selected.album.data.priority,
vm.selected.album.data.memo);
})
}
function selectTrack(album, track){
vm.selected.album = album;
vm.selected.track = track;
vm.testingAlbumSelected = false;
}
function editAlbum(album, index){
getAlbumTracks(album.slug, index);
vm.selected = album;
}
function saveRelease(){
// Call the PUT request to update the release metadata and refresh the page
// so that the Album list gets updated with the latest changes
var url = 'http://localhost:8080/api/releases/' + vm.selected.album.slug;
$http.put(url, vm.formAlbum).then(function(saveAlbumResponse){
if(saveAlbumResponse.status === 202){
//successfully saved response on backend
// Update the current models to show the newer data
vm.album.data = vm.formAlbum;
console.log("album array vm.albums = "+vm.albums);
}
})
}
})();
Any idea why ?
try remove "var vm=this" line. And rename vm.xxxx to $scope.xxxx in your controller.
in the view: remove the "vm."
I'm really new to Angular and i'm trying to create a list of user transactions that presents the time of the action and the user's name. In my audit API I have an action ID and the User FK which associates with my User API and i'm displaying it as follows:
HTML
<table>
<thead>
<tr>
<th>
Date/Time
</th>
<th>
User
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="audit in audit.data>
<td>{{audit.audit_date_time}}</td>
<td>**{{audit.audit_user_fk}}**</td> **<--I need the name not the ID here**
</tr>
</tbody>
</table>
My Apis are as follows:
AUDIT
[
{
"audit_id": "1",
"audit_date_time": "2016-01-28 12:46:20",
"audit_user_fk": "97"
}
]
USER
[
{
"user_id": "97",
"user_full_name": "Mr.User",
}
]
Controller, which is working fine GETting the data from each API:
app.controller('auditControl', ['$scope','auditService', 'userService', function ($scope, auditService, userService) {
var auditLogs = auditService.query(function () {
$scope.audit.data = auditLogs;
});
var user = userService.query(function () {
$scope.auditUser = user;
});
}]);
So my main issue i'm having is getting the user name in the table instead of the foreign key value. I've stripped out a lot of this just so we can focus on the main problem. Getting the user name from the user API, based on the FK in the Audit API and repeated based on the items in the Audit API.
Any help greatly appreciated and apologies for the noob question!
Create a custom filter.
app.filter("lookupUser", function() {
function lookup (idNum, userList) {
var userName = "UNKNOWN";
angular.forEach(userList, function(user) {
if ( user.user_id == idNum ) {
userName = user.user_full_name;
};
});
return userName;
};
return lookup;
});
Then in your template:
<tr ng-repeat="audit in audit.data>
<td>{{audit.audit_date_time}}</td>
<td>{{audit.audit_user_fk | lookupUser : auditUser }}</td>
</tr>
You could do something like this:
Controller:
app.controller('auditControl', ['$scope','auditService', 'userService', function ($scope, auditService, userService) {
var auditLogs = auditService.query(function () {
$scope.audit.data = auditLogs;
});
var user = userService.query(function () {
$scope.auditUser = user;
});
$scope.getUserName = function (id) {
var result = $scope.users.filter(function( user ) {
return user.user_id == id;
});
if (angular.isDefined(result) && result.length > 0) {
return result[0].user_full_name;
} else {
return "--";
}
}
}]);
HTML
<table>
<thead>
<tr>
<th>
Date/Time
</th>
<th>
User
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="audit in audit.data">
<td>{{audit.audit_date_time}}</td>
<td>**{{getUserName(audit.audit_user_fk)}}**</td> **<--I need the name not the ID here**
</tr>
</tbody>
</table>
I don't know where the users array are, so I called $scope.users.
I'm trying to generate HTML table from json in AngularJS.
I receive JSON in format like this:
My Service for getting the data looks like this :
customAPI.getUsers = function() {
return $http({
method: 'JSONP',
url: 'http://arka.foi.hr/WebDiP/2013_projekti/WebDiP2013_069/api/admin/users.php'
});
};
and controller for that code looks like this
controller('usersController', function($scope, customAPIservice) {
$scope.filterName = null;
$scope.usersList = [];
/*Search*/
$scope.searchFilter = function(user) {
var keyword = new RegExp($scope.filterName, 'i');
return !$scope.filterName || keyword.test(user.korisnici.korisnik_ime) || keyword.test(user.korisnici.korisnik_prezime);
};
customAPIservice.getUsers().success(function(response) {
$scope.usersList = response.korisnici;
});
});
and my view looks like this :
<input type="text" ng-model="nameFilter" placeholder="Trazi..."/>
<h2 >Korisnici</h2>
<table>
<thead>
<tr>
<th colspan="6">Korisnici sustava</th>
</tr>
<th>Surname</th>
</thead>
<tbody>
<tr ng-repeat="user in usersList| filter: searchFilter">
<td>{{$index + 1}}</td>
<td>{{user.korisnik.korisnik_prezime}}</td>
<td>{{user.korisnik.korisnik_username}}</td>
</tr>
<tr ng-show="usersList == ''">
<td colspan="5">
<img src="img/ajax-loader.gif" />
</td>
</tr>
</tbody>
</table>
I think I messed up somewhere with binding the data with the view but I' still pretty new with angular so I can't find what is wrong. Also I've looked up over internet and couldn't find anything.Please help.
You are not correctly access the properties in your data. Use:
/*Search*/
$scope.searchFilter = function(user) {
var keyword = new RegExp($scope.filterName, 'i');
return !$scope.filterName || keyword.test(user.korisnik.korisnik_ime) || keyword.test(user.korisnik.korisnik_prezime);
};