I am trying to do a test app based on app from tutorial https://docs.angularjs.org/tutorial/step_00 . It works fine but I have with post method.
index.html
...
<div class="control_panel" ng-controller="phonecatControllers">
<button class="btn btn-default" ng-click="chiliSpicy()">Chili!</button>
<button class="btn btn-default" ng-click="sendData()">send!</button>
</div>
...
controllers.js
'use strict';
var phonecatControllers = angular.module('phonecatControllers', []);
phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http', '$log',
function ($scope, $http, $log) {
$http.get('http://localhost:8080/webapp/rest/myresource/posts').
success(function (data) {
$scope.posts = data;
});
$scope.data = "hello world";
$scope.chiliSpicy = function () {
$log.info('chili function');
};
$scope.sendData = function () {
$http.post('http://localhost:8080/webapp/rest/myresource/', {'data' : $scope.data} )
.succes(function (data, status, headers, config) { // !!! here is line 39
$log.info('sent');
})
.error(function (data, status, headers, config) {
$log.error('not sent')
});
};
}]);
Get method works ok (showed html code does not contain its usage), also chiliSpicy function works. But sendData function throws error (where success function is)
TypeError: undefined is not a function
at l.$scope.sendData (http://localhost:8080/webapp/controllers.js:39:18)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:198:424
at chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:798:21
at l.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:126:84)
at l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:126:310)
at l.scopePrototype.$apply (chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:1478:22)
at HTMLButtonElement.<anonymous> (chrome-extension://ighdmehidhipcmcojjgiloacoafjmpfk/dist/hint.js:797:25)
at HTMLButtonElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js:32:363)
Actually, the server receives data, but success function do not pass. Any idea? Thanks.
Misspelled success, written as succes.
There is typo. It should be success instead of 'succes'
phonecatControllers.controller('PhoneListCtrl', ['$scope', '$http', '$log',
function ($scope, $http, $log) {
$http.get('http://localhost:8080/webapp/rest/myresource/posts').
success(function (data) {
$scope.posts = data;
});
$scope.data = "hello world";
$scope.chiliSpicy = function () {
$log.info('chili function');
};
$scope.sendData = function () {
$http.post('http://localhost:8080/webapp/rest/myresource/', {'data' : $scope.data} )
.success(function (data, status, headers, config) { // !!! here is line 39
$log.info('sent');
})
.error(function (data, status, headers, config) {
$log.error('not sent')
});
};
}]);
Related
I want to inject my service into my controller and just see my console log (in the Auth Service), but I'm getting this error: Argument 'myAppController' is not a function, got undefined. What am I doing wrong?
In my main.js file I have:
var myApp = angular.module('myApp',['ngRoute', 'ui.router']);
myApp.controller('myAppController', ['$scope', function($scope, AuthService) {
console.log('controller');
AuthService.console();
...
In my services.js file I have:
var myApp = angular.module('myApp',[]);
myApp.service('AuthService', function(){
this.console = function(){
console.log('in the AuthService');
}
});
Loading the files in my index.html file as:
<script src="js/main.js"></script>
<script src="js/services.js"></script>
Gotta declare it as a string too for the injection:
myApp.controller('myAppController', ['$scope', 'AuthService', function($scope, AuthService) {
Define MyApp Like this
var myApp = angular.module("myApp", ['ngRoute', 'ui.router']);
myApp.controller('myAppController', function ($scope, ajaxService) {
ajaxService.ajaxGetWithData(url).then(function (data) {
$scope.Data= data;
});
});
app.service('ajaxService', function ($http, $q) {
this.ajaxGetWithData = function (url) {
var deferred = $q.defer();
$http({
method: 'POST', url: url, data: $.param(User),
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
})
.success(function (data) {
if (data != null) {
deferred.resolve(data);
}
})
.error(function (err) {
deferred.reject(err);
});
return deferred.promise;
}
});
When i post a detail to an api with angularJs, i got an error like TypeError: $scope.posts.push is not a function now how i fix that?
My post code is :
AdminApp.controller('AddVehicleModalCtrl', ['$scope', '$rootScope', '$modalInstance','$http','toaster', function ($scope, $rootScope, $modalInstance,$http,toaster) {
$scope.create = function(){
$http.post(AppCore.getGlobalApiUrl()+'vehicle_type', {"vehicle_type": $scope.post.vehicle_type})
.success(function(response, status, headers, config){
$modalInstance.dismiss('cancel');
toaster.pop('success', "post", "done");
$scope.posts.push(response.posts);
$scope.$apply();
})
.error(function(response, status, headers, config){
$scope.error_message = response.error_message;
});
};
$scope.cancel = function () {
$scope.post = "";
$modalInstance.dismiss('cancel');
};
}]);
You haven't defined $scope.posts as an array anywhere. Above your $scope.create definition, just throw in an initializing statement like
$scope.posts = [];
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have started to learn something about AngularJS. I managed to create some simple controllers, but I would like to do a bit of refactoring and create also a factory.
Here is one of my js files:
angular
.module('myApp', ['ngResource'])
.factory('UserFactory', ['$http', function ($http) {
return {
getOne: function () {
$http({method: 'GET', url: 'http://localhost:8080/login/login'})
.success(function (data, status, headers, config) {
console.info(data);
return data;
})
.error(function (data, status, headers, config) {
alert("failure");
});
}
}
}])
.controller('UserController', ['$scope', 'UserFactory', function ($scope, UserFactory) {
$scope.user = UserFactory.getOne();
}]);
The program correctly prints the data to the console received from the servlet at that line: console.info(data);
But the controller does not return anything to the view. I put here also console.info(UserFactory.getOne()) and it prints undefined.
Where is my coding mistake?
getOne needs to return a value, and in this case it'll be a promise from $http. The success method should return the value needed by the controller.
.factory('UserFactory', ['$http', function ($http) {
return {
getOne: function () {
return $http({method: 'GET', url: 'http://localhost:8080/login/login'})
.success(function (data, status, headers, config) {
return data;
});
}
}
}]);
Now in your controller you can handle that result.
app.controller('UserController', ['$scope', 'UserFactory', function ($scope, UserFactory) {
UserFactory.getOne().then(function(data){
$scope.user = data;
});
}]);
The success and failure methods are depreciated. You should try using then instead.
.factory('UserFactory', ['$http', function ($http) {
return {
getOne: function () {
return $http({method: 'GET', url: 'http://localhost:8080/login/login'})
.then(function (response) {
return response.data;
});
}
}
}]);
Your factory return at the wrong place, so it return undefined. you can fix it by handling success in controller itself. try this.
var app = angular.module('plunker', []);
app.factory('UserFactory', ['$http', function ($http) {
return {
getOne: function (callback) {
$http({method: 'GET', url: 'request_url'})
.success(function (data, status, headers, config) {
callback(data, status, headers, config);
})
.error(function (data, status, headers, config) {
alert("failure");
});
}
}
}]);
app.controller('UserController', ['$scope', 'UserFactory', function ($scope, UserFactory) {
UserFactory.getOne(function(data){
$scope.user = data;
});
}]);
WORKING URL : DEMO
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'm trying to use angular promise using $q that is wrapped in 'service' and call it from my controller.
Here is the code:
var myController = function ($scope, myService) {
$scope.doSomething = function (c, $event) {
$event.preventDefault();
myService.method1(c).then(function (rslt) {
alert(rslt);
}, function (err) {
alert(err);
}).then(function () {
//clean up
});
};
};
var myApp = angular.module('myApp', [])
.factory('myService', function($q) {
function _method1(c) {
var dfr = $q.defer();
var dt = { sc: c };
$.ajax({
type: "POST",
url: "mypage.aspx/mymethod",
data: JSON.stringify(dt),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
dfr.resolve('actions sucess');
},
error: function (msg) {
dfr.reject(msg);
}
});
return dfr.promise;
}
return { method1: _method1 };
}).controller('myController', myController);
The problem is that ' alert(rslt);' piece of code is never executed.
Service is called and data is updated but first 'then' function is not reached on first click.
What am I doing wrong?
Any help appreciated.
I would recoomend you to use $http and $resource instead of $.ajax
Heres an example of $http
myApp.factory('MyService',
[
'$http',
'$q',
'$resource',
function (
$http,
$q,
$resource
) {
return {
doSomething : function (somedata) {
var deferred = $q.defer();
$http({ method: 'POST', url: '"mypage.aspx/mymethod"', data: somedata }).
success(function (data, status, headers, config) {
deferred.resolve(true);
}).
error(function (data, status, headers, config) {
deferred.resolve(false);
});
return deferred.promise;
}
};
}]);
Just add the dependency to $rootScope and call $rootScope.$apply() in both callbacks from $.ajax():
success: function () {
dfr.resolve('actions sucess');
$rootScope.$apply();
}, ...
But better yet, use Angular's $http service.