I am newbie to angularJS. I have started learning with CRUD operation. I am getting a problem that when I delete an entry then the page should reload
I have gone through $location and $route too. and implementing as follow :
config
app.config( function ( $locationProvider, $routeProvider ) {
$locationProvider.html5Mode(true);
$locationProvider.hashPrefix = '!';
$routeProvider.when('/', {
templateUrl: '/views/index.html',
controller: 'MainCtrl'
});
$routeProvider.when('/this',{
templateUrl: '/views/about.html',
controller: 'MainCtrl'
});
});
and when action success then I am writing as :
$location.path('/this');
but when I do this then the url changes from http://localhost/someapp to http://this but the page does not refresh. What should I do in this case please help me guys ?
Edit :
Here is my deletion code :
$scope.deletecode = function (id) {
name = '';
if (confirm("are you sure to Delete the name")) {
$http({
method: 'POST',
url: 'rohit.php',
data: {
"name": name,
"id": id,
"delete": "true"
},
}).
success(function (data, status, headers, config) {
alert("data deleted successfully");
$location.path('/this');
}).
error(function (data, status, headers, config) {
alert("Unable to load data.");
});
} else {
alert("Data deletion cancelled by user ... ");
}
};
On init I am getting the data from a php file :
$http({
method: 'GET',
url: 'test.php'
}).
success(function (data, status, headers, config) {
$scope.samples = data;
}).
error(function (data, status, headers, config) {
alert("Unable to load data.");
});
all the data is stored in $scope.samples which returns two things user_id and name
Your http request is deleting the item from your server, but you are not deleting it from your client-side code, which is why your view is not updating. You want to remove it from you client-side code as well once it has been removed from the server:
// all items in an array
$scope.items = [item1, item2];
// delete an item
$scope.deletecode = function (id) {
name = '';
if (confirm("are you sure to Delete the name")) {
$http({
method: 'POST',
url: 'rohit.php',
data: {
"name": name,
"id": id,
"delete": "true"
},
}).
success(function (data, status, headers, config) {
alert("data deleted successfully");
// at this point, the item has been deleted from your server
// remove it from $scope.items as well
// removes 1 item at index idx
$scope.items.splice(idx, 1);
}).
error(function (data, status, headers, config) {
alert("Unable to load data.");
});
} else {
alert("Data deletion cancelled by user ... ");
}
};
Related
I'm having this situation I'm iterating over a json response from an endpoint:
chunk of controller code:
$http({
method: 'GET',
url: 'http://mywebsite.com/api/v1/stores/'
}).
success(function(data, status, headers, config) {
$scope.stores = data;
}).
error(function(data, status, headers, config) {
$scope.name = 'Error!';
});
and on my html view side I've got this:
<tbody>
<tr ng-repeat="store in stores">
<td>{{store.name}}</td>
<td> {{store.type}} </td>
<td><span ng-repeat="client in retrieveClientName(store.client_id)">
{{client.name}}
</span>
</td>
<td>{{store.address}}</td>
</tr>
</tbody>
As you can see I'm trying to retrieve the client name using a function that receives an store.client_id from the values inside the stores array. Normally using a function triggered by a ng-click will be easy but how can I achieve this "on the fly" while I'm iterating?.
Because executing this I get a kind of infinite loop that breaks all apart.
here is the code of the function that returns client name on the controller side:
$scope.retrieveClientName = function(id) {
$http({
method: 'GET',
url: 'http://mywebsite.com/api/v1/clients?client_id='+id
}).
success(function(data, status, headers, config) {
return $scope.clients=data;
}).
error(function(data, status, headers, config) {
$scope.name = 'Error!';
});
}
I have also try using mg-init directive
<td ng-init="clients=retrieveClientName(store.client_id)"><span ng-repeat="client in clients">{{client.name}}</span></td>
One way would be get all data when you get the stores back
$http({
method: 'GET',
url: 'http://mywebsite.com/api/v1/stores/'
}).
success(function(data, status, headers, config) {
$scope.stores = data;
angular.forEach($scope.stores, function(store){
$scope.retrieveClientName(store.client_id).then(function(clients){
store.clients = clients;
});
});
}).
error(function(data, status, headers, config) {
$scope.name = 'Error!';
});
Edit: I would change the structure a bit for cleaner code
$scope.retrieveClientName = function(store) { // pass in store so we can attach results here
$http({
method: 'GET',
url: 'http://mywebsite.com/api/v1/clients?client_id='+store.client_id
}).
success(function(data, status, headers, config) {
return store.clients = data; // attach result in object
}).
error(function(data, status, headers, config) {
$scope.name = 'Error!';
});
}
$http({
method: 'GET',
url: 'http://mywebsite.com/api/v1/stores/'
}).
success(function(data, status, headers, config) {
$scope.stores = data;
angular.forEach($scope.stores, function(store){
$scope.retrieveClientName(store); // no need .then here
});
}).
error(function(data, status, headers, config) {
$scope.name = 'Error!';
});
<tbody>
<tr ng-repeat="store in stores">
<td>{{store.name}}</td>
<td> {{store.type}} </td>
<td><span ng-repeat="client in store.clients"> <!-- use data here -->
{{client.name}}
</span>
</td>
<td>{{store.address}}</td>
</tr>
</tbody
You must understand that $http jest asynchronous, so Your response will be back after all ng-repeat, so such thing must be done in controller in $q.all and after that render view with ng-repeat.
So do foreach on stores and in foreach add to array, next use this array in $q.all, after $q.all render view.
The retrieveClientName function is wrong: the $http return a promise, the return value of success callback is not the return value of the function and you can't bind the ng-repeat to a promise, try this one:
$scope.retrieveClientName = function(id) {
return $resource('http://mywebsite.com/api/v1/clients?client_id='+id).query();
}
Don't forget to include the ngResource dependency.
I'm trying to read a properties file in angular, It's neccesary to have this file at the root of my project without any kind of angular stuffs, just a simple file, like java.
This is what I'm doing.
Creating a angular.properties file.
angular.properties
{
"url": "http://localhost"
}
This is my controller where I invoke my service method:
controller
captchaService
.all()
.then(function(data) {
...
}, function (data) {
...
});
This is my service class:
service
'use strict';
angular.module('app.service', [])
.factory('myService',
['$http', '$q',
function ($http, $q) {
var _URL = "";
function getValuesFromProperties() {
$http({
method : 'GET',
url : 'angular.properties'
}).success(function (data, status, headers, config) {
_URL = data.url;
}).error(function (data, status, headers, config) {
...
});
}
function all() {
getValuesFromProperties();
var deferred = $q.defer(),
promise = deferred.promise;
sessionStorage.removeItem('X_CAPTCHA_TOKEN');
$http({
method : 'POST',
url : _URL
}).success(function (data, status, headers, config) {
...
}).error(function (data, status, headers, config) {
...
});
return promise;
}
return {
all : all,
getValuesFromProperties : getValuesFromProperties
};
}]);
But here in my services class I have two $http running on an asynchronous way for that reason I can not get the value of url everything else works perfect. How can resolve this? Maybe there is another way to do this. I don't want to create a constant class because this file it's placed at the root of the project and it will be configure for others, they don't need to enter inside a lot of folders and check the code, search and edit. Any idea?
I am trying to build a page of WordPress posts, showing 4 initially and then lazy load these in onclick of a "Load More" button. This list will be filterable via angular.
I am using the json rest api plugin for WordPress, and my angular app is currently:
var myapp = angular.module( 'myapp', [] );
// Set the configuration
myapp.run( ['$rootScope', function($rootScope) {
// Variables defined by wp_localize_script
$rootScope.api = aeJS.api;
}]);
// Add a controller
myapp.controller( 'mycontroller', ['$scope', '$http', function( $scope, $http ) {
// Load posts from the WordPress API
$http({
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]' : 4
},
}).
success( function( data, status, headers, config ) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {});
$scope.loadmore = function(){
$scope.posts = $scope.posts.concat(data);
}
}]);
I am just a bit clueless with how to get the next 4 posts each time the load more button is clicked. I have setup a loadmore function which I am calling on click of the button:
<button ng-click="loadmore()">Load more articles</button>
Any advice would be appreciated, thanks.
Basically you need to use paging which has already implemented in wordpress API.
You need to increment your posts_per_page on each ajax call.
Controller
myapp.controller('mycontroller', ['$scope', '$http', function($scope, $http) {
var count = 0;
$scope.posts = []; //setted as blank
$scope.getData = function() {
// Load posts from the WordPress API
$http({
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]': 4,
'filter[page]': ++count
},
}).
success(function(data, status, headers, config) {
$scope.posts = $scope.posts.concat(data);
}).
error(function(data, status, headers, config) {});
};
$scope.loadmore = function() {
$scope.getData();
};
}]);
Done - with the help from a friend, this solution is working nicely:
var myapp = angular.module( 'myapp', [] );
// Set the configuration
myapp.run( ['$rootScope', function($rootScope) {
// Variables defined by wp_localize_script
$rootScope.api = aeJS.api;
}]);
myapp.controller('mycontroller', ['$scope', '$http', function($scope, $http) {
$scope.init = function() {
$http({ // Load posts from the WordPress API
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]' : 4
},
}).
success( function( data, status, headers, config ) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {});
};
var page = 2;
$scope.getData = function() {
$http({ // Load posts from the WordPress API
method: 'GET',
url: $scope.api,
params: {
'filter[posts_per_page]': 4,
'page': page
},
}).
success(function(data, status, headers, config) {
$scope.posts = $scope.posts.concat(data);
page++;
}).
error(function(data, status, headers, config) {});
};
$scope.loadmore = function() {
$scope.getData();
};
}]);
I am new to AngularJS and wanted to try out the $resource functionality.
I have this code:
.factory('GetTasksService', function($resource, BASE_URL) {
return $resource(BASE_URL + 'api/tasks');
})
.controller('TasksCtrl', function ($scope, $http, BASE_URL, GetTasksService) {
$scope.tasks = GetTasksService.query();
$scope.getTasks = function () {
$http({ url: BASE_URL + 'api/tasks', method: 'GET' })
.success(function (data, status, headers, config) {
$scope.tasks = data;
})
.error(function (data, status, headers, config) {
alert("call did not work");
});
}
});
The getTasks function works as expected - returning an array of:["taska", "taskb"] as it should.
The GetTasksService.query() however returns an array of [{"0":"t","1":"a","2":"s","3":"k","4":"a"}, {"0":"t","1":"a","2":"s","3":"k","4":"b"}]
Can anyone tell me what I am doing wrong?
There is an option when specifying an action for an ngResource called isArray;
The default action query sets this as true by default, so you need to set set the action like:
query : {
method : 'GET',
isArray : false
}
I am new in angularjs. I am try to send a get request to my Web-Api 2 project. But I don't understand why its continuously call my method. I am following AngularJs $http for this.
Here is my error:
My Code is :
<script src="~/Scripts/jquery-2.1.0.js"></script>
<script src="~/Scripts/angular.min.js"></script>
<script>
function loginCtrl($scope, $http) {
$scope.name = function () {
console.log("Add Call");
$http({ method: 'GET', url: 'http://localhost:15229/api/values' }).
success(function (data, status, headers, config) {
console.log(data);
}).
error(function (data, status, headers, config) {
console.log(data);
});
};
}
</script>
<div lang="en" ng-app="" ng-controller="loginCtrl">
{{name()}}
</div>
You don't give enough context information for me to be sure of what you want to achieve. Especially I don't know what returns your api. So I will assume It returns the value you want to display. Your code should look more like this:
function loginCtrl($scope, $http) {
$scope.init = function () {
console.log("Add Call");
$http({ method: 'GET', url: 'http://localhost:15229/api/values' }).
success(function (data, status, headers, config) {
console.log(data);
$scope.name = data;
}).
error(function (data, status, headers, config) {
console.log(data);
});
};
}
<div lang="en" ng-app="" ng-controller="loginCtrl" ng-init="init()">
{{name}}
</div>
You should affect $scope.name in the success callback.
name should be a variable, not a function.
And the ng-init attributes defines the method to be invoked when instanciating the controller. In this case it will invoke the init() method of your controller.