Here's my json:
[
{
"name": "AAAAAA",
"date": "28-03-2016",
},
{
"name": "BBBBBB",
"date": "20-12-2016",
},
{
"name": "CCCCCC",
"date": "09-01-2016",
},
{
"name": "DDDDDD",
"date": "21-07-2016",
}
]
My javascript:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('names.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function() {
$http({
method: 'POST',
url: 'serverUrl',
data: name.name,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
My HTML:
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.time | date}}</td>
<td><button ng-click="postfunction()">POST</button></td>
</tr>
</tbody>
What I want do is when I click the button "POST" name.name post to server. I try $http.post in postfunction(), but I get "$http is not defined" in console.
You forgot to inject $http into your controller
app.controller('FirstCtrl', function($scope, service, $http) {
^
You have to inject $http service in your controller 'FirstCtrl' as below:
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function(name) {
$http({
method: 'POST',
url: 'serverUrl',
data: name,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
};
});
Also additionally along with passing the argument to the post function, you have to pass the 'name' in the HTML as below, this is because, in your controller, 'name' is never defined.
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.time | date}}</td>
<td><button ng-click="postfunction(name.name)">POST</button></td>
</tr>
</tbody>
Related
When the below code is run nothing shows in my console to indicate anything went wrong, but as you can see in listService it's alerting withing the results, but the alert shows as "undefined".
I'm ultimately trying to get it to run a repeat to list all the Organizations on the view. Any help is appreciated!!
Here is my factory.
app.factory("listService", ["$rootScope", "$http", "$location", "$routeParams",
function($rootScope, $http, $location, $routeParams) {
var siteURL = "jdfyhgyjdfghyjdgfyhkjyhjk";
var svc = {};
var data = null;
svc.getListItems = function(listName) {
$http({
url: siteURL + "/_api/web/lists/GetByTitle('" + listName + "')/items",
method: "GET",
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function(response, status, headers, config) {
data = response.data.d.results;
alert(data);
},
error: function(response, status, headers, config) {
$rootScope.error = status;
}
});
}
return svc;
}
]);
Here is my controller.
app.controller("readOrganizationsCtrl", ["$scope", "$http", "$location", "$routeParams", "listService",
function($scope, $http, $location, $routeParams, listService) {
$scope.organizations = listService.getListItems('Organizations');
}
]);
And lastly here is my view.
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search organizations" data-ng-model="search" />
</div>
<table class="table table-stripped table-hover">
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="organization in organizations | filter:search" data-ng-click="editOrganization($index)">
<td>{{organization.Title}}</td>
</tr>
</tbody>
</table>
<div class="form-group">
<button data-ng-click="addOrganization()" class="btn btn-primary">Add Organization</button>
</div>
{{"Error:" + error}}
after calling $http in controller you can easily get all your organizations from siteURL, here is working code:
JS:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, $http) {
$http({
method: 'GET',
url: 'organizations.json',
headers: {
withCredentials: true,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
},
})
.then(function successCallback(data) {
$scope.organizations = data.data;
console.log($scope.organizations)
}, function errorCallback(response) {
console.log(response);
console.log('error');
});
});
HTML:
<tbody>
<tr data-ng-repeat="organization in organizations | filter:search" data-ng-click="editOrganization($index)">
<td>{{organization.name}}</td>
</tr>
</tbody>
plunker: http://plnkr.co/edit/aP7fLU1tfWwmZdCAYzIf?p=preview
Or, if you want to do it by factory, you can do it this way:
app.controller('MainCtrl', function($scope, $http, factory) {
factory.getOrganizations()
.then(function(data){
$scope.organizations = data.data;
console.log($scope.organizations)
})
.catch(function(){
})
});
app.factory('factory',function($http){
return {
getOrganizations: function(){
return $http.get('organizations.json');
}
};
})
plunker: http://plnkr.co/edit/UJUrTIGHGtjjccGAnHlk?p=preview
I was trying to clean my angular app code up. So I moved all the controllers in their own files. But when I moved the controllers, my main app stoped working and started throwing the exception below -
Error: $injector:modulerr
Module Error
Then I tried searching for the why the module won't load but with no luck.
main.js /*File where app module is declared*/
var app = angular.module('app', ['ngRoute','thatisuday.dropzone','UserController','LinkController','articleController']);
I tried injecting the dependency for the controller files.
Controllers:
Link Controller
var app = angular.module('app');
app.controller('LinkController', ['$scope','$http','$sce',function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*First AJAX request which gets all the links and categories for the user*/
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
$scope.getUser = function () {
$http({
method: 'GET',
url: '/users'
}).then(function successCallback(response) {
$scope.user = response.data;
}, function errorCallback(response) {
});
};
$http({
method: 'GET',
url: '/links'
}).then(function successCallback(response) {
this.orderProp = 'age';
/*the response is saved in scope variables*/
$scope.links = response.data[0];
$scope.categories = response.data[1];
$scope.categorytolink = response.data[2];
}, function errorCallback(response) {
console.log('There was a problem! Refresh!');
});
/*AJAX request for getting the recommendations according to the most viewed stars*/
$http({
method: 'GET',
url: '/recommendations/top'
}).then(function successCallback(response) {
$scope.recommendations = response.data;
}, function errorCallback(response) {
});
/*AJAX request when a user clicks a link retrieves the link data*/
$scope.getLinkData = function (link) {
$http({
method: 'GET',
url: "/proxy",
headers: {
"X-Proxy-To": link.rss_link
}
}).then(function successCallback(response) {
/*AJAX request: add a star to the link*/
$http.post('/links/' + link.id + '/views/add', {'link': link}).then(function successCallback(data, status, headers, config) {
// Manually increment star for link just clicked
var $data;
$data = data.data;
$scope.link = $data;
console.log('200 OK! Star added');
}, function errorCallback() {
console.log('Error!');
});
/*The data will be retrieved and will be sorted according to the requirements of welcome.blade*/
$myXml = response.data;
$xmlObj = $.parseXML($myXml);
$newsItems = [];
$channelImage = $($xmlObj).find("channel>image");
/*the information of the link is sorted */
$linkData = {
"title": $channelImage.find("title").text(),
"link": $channelImage.find("link").text(),
"imgurl": $channelImage.find("url").text()
};
/*the data is sorted below*/
$.each($($xmlObj).find("item"), function (index, value) {
$newsItems.push({
"title": $(value).find("title").text(),
"description": $(value).find("description").text(),
"link": $(value).find("link").text(),
"date_published": moment($(value).find("pubDate").text()).format('MMMM Do YYYY'),
"time_published": moment($(value).find("pubDate").text()).format('h:mm:ss a'),
"guid": $(value).find("guid").text()
})
});
$scope.newsItems = $newsItems;
$scope.linkData = $linkData;
}, function errorCallback(response) {
});
};
/*Create a category private to the user*/
$scope.create_category = function (category) {
/*AJAX request: adds a new category*/
$http.post('/categories/new', {'category': category}).then(function successCallback(response) {
/*AJAX request: Updates the categories for the use of new category*/
$http({
method: 'GET',
url: '/categories'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
});
}, function errorCallback(response) {
});
};
}]);
User Controller
var app = angular.module('app');
app.controller("UserController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
$scope.dzOptions = {
paramName: "file",
dictDefaultMessage: "<h4><i class='fa fa-camera'></i> <b>Upload</b></h4>",
createImageThumbnails: false,
autoDiscover: false
};
$scope.dzCallbacks = {
'sending': function (file, xhr, formData) {
formData.append('_token', $('#csrf-token').val());
},
'success': function (file, response) {
$scope.user = response;
$.notify("Profile photo changed!", "success", {autoHide: true, autoHideDelay: 500});
}
};
/*Update user info*/
$scope.updateUser = function () {
/*AJAX request: update user info*/
$http.post('/users/update', {
'name': $scope.user.name,
'username': $scope.user.username,
'email': $scope.user.email
}).then(
function successCallback(data) {
$scope.user = data;
$.notify("User updated!", "success", {autoHide: true, autoHideDelay: 500});
console.log('200 OK! User updated');
}, function errorCallback() {
console.log('Error!');
});
};
}]);
Article Controller
var app = angular.module('app');
app.controller("articleController", ['$scope','$http','$sce', function ($scope, $http, $sce) {
/*Sce declaration required for proxy settings*/
$scope.renderHtml = function (html_code) {
return $sce.trustAsHtml(html_code);
};
$scope.trustSrc = function (src) {
return $sce.trustAsResourceUrl(src);
};
/*Populates the comments for particular
* */
$scope.populatecomments = function (newsItem) {
$http({
method: 'GET',
url: '/articles/' + newsItem.guid + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
}, function errorCallback(response) {
});
};
$scope.data = [];
$scope.comment = [];
$scope.btn_add = function (newsItem) {
if ($scope.txtcomment != '') {
$scope.data.push({
"comment": $scope.txtcomment,
"guid": newsItem.guid
});
$http.post('/comments/new', {
"comment": $scope.txtcomment,
"guid": newsItem.guid
}).then(function successCallback() {
var encodedURI = encodeURIComponent(newsItem.guid);
$http({
method: 'GET',
url: '/articles/' + encodedURI + '/comments'
}).then(function successCallback(response) {
$scope.comments = response.data;
$scope.txtcomment = "";
}, function errorCallback(response) {
});
}, function errorCallback() {
console.log('Error comment!');
});
}
};
$scope.savearticle = function (newsItem) {
$http.post('/saved-articles/save', newsItem).then(function successCallback(response) {
/*console.log(document.getElementById("save/"+newsItem.guid).className="disabled");*/
}, function errorCallback(response) {
});
}
/**
* The saved articles by the user will be retrieved when a button clicked
*/
$scope.getSavedArticles = function () {
/*AJAX request: retreive the saved the saved articles for the user*/
$http({
method: 'GET',
url: '/saved-articles'
}).then(function successCallback(response) {
$scope.linkData = null;
$scope.newsItems = response.data;
}, function errorCallback(response) {
});
};
}]);
HELP needed!
Yo do not need to declare module in each controller file. Remove the line in each controller
var app = angular.module('app');
You are injecting controller in you module like dependency.
Change your main.js file to this:
var app = angular.module('app', ['ngRoute','thatisuday.dropzone']);
#Sajeetharan is right you do not need module declaration in all controllers.
Since you are using laravel according to your comment. ( It will conflict with your blade template because both use same {{ }} for variables )
There are two ways to do this:
Change the Angular Tags
var app = angular.module('app', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
Now Laravel will use the {{ variableName }} and Angular will use <%
variableName %>.
Change the Laravel Blade Tags
Blade::setContentTags('<%', '%>');// for variables and all things Blade
Blade::setEscapedContentTags('<%%', '%%>');// for escaped data
Variables will be: <% $variable %>. Comments will be: <%-- $variable
--%>. Escaped data will look like: <%% $variable %%>.
You can check this Tutorial for more info.
[
{
"name": "AAAAAA",
"date": "28-03-2016",
},
{
"name": "BBBBBB",
"date": "20-12-2016",
},
{
"name": "CCCCCC",
"date": "09-01-2016",
},
{
"name": "DDDDDD",
"date": "21-07-2016",
}
]
My javascript:
var app = angular.module('app', []);
app.service('service', function($http, $q){
var deferred = $q.defer();
$http.get('names.json').then(function(data){
deferred.resolve(data);
});
this.getNames = function() {
return deferred.promise;
}
});
app.controller('FirstCtrl', function($scope, service, $http) {
var promise = service.getNames();
promise.then(function (data) {
$scope.names = data.data;
console.log($scope.names);
}
);
$scope.postfunction = function(data) {
$http({
method: 'POST',
url: 'serwerUrl' ,
data: {"name":$scope.name},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data){
console.log('data success');
});
HTML:
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.date}}</td>
<td><button ng-click="postfunction(names)">POST</button></td>
</tr>
</tbody>
What I want do is when I click the button "POST" name.name post to server. I try function postfunction(), but it didn't post to server, in my console everything is ok, but name.name don't post to server.
The $scope.name you're trying to send isn't defined anywhere.
You'll want to change names here into name:
...
<td><button ng-click="postfunction(name)">POST</button></td>
...
and in your postfunction ditch $scope.name altogether and do this instead (also use .then instead of .success, .success is deprecated):
$scope.postfunction = function(name) {
$http({
method: 'POST',
url: 'serwerUrl' ,
data: {"name": name},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(data){
console.log('data success');
});
}
Are you sure that the API takes content type application/x-www-form-urlencoded? It is best to use the Angular default of application/json? If you must urlencode the data, use the $httpParamSerializerJQLike Service.
.controller(function($http, $httpParamSerializerJQLike) {
//...
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
});
-- AngularJS Param Serializer API Reference
I have this json data:
{
status: "SUCCESS",
data: [
{
FirstName: "Student ",
LastName: "1",
Id: 1,
ObjectState: 0
},
{
FirstName: "Student ",
LastName: "2",
Id: 2,
ObjectState: 0
}
}
]
}
I have tried like this,in my controller and in the view:
app.js:
.controller("etudCtrl",["$scope", "$http", function ($scope, $http) {
var i;
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
for(i=0;i<data.length;i++){
$scope.paged = data[i].data; // response data
console.log($scope.paged+" $scope.paged");
}
$scope.currentPageStores= $scope.paged;
console.log($scope.currentPageStores+" values");
console.log("success");
}).error(function (data, status, headers, config) {
console.log("data error ...");
});
}])
Students.html:
<table>
<thead>...</thead>
<tbody data-ng-controller="etudCtrl">
<tr ng-repeat="store in currentPageStores" >
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
</tr>
</tbody>
</table>
and this what I get in console:
values
success
I didn't get any data in console or in the Table :(
any help please
thanks
Update:
I try with this:
$rootScope.usersData = angular.toJson(data.data);
console.log($rootScope.usersData+" my data");
I get all the data that I want to display in console
Update2:
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
console.log(JSON.stringify(data)+"myData");
for(i=0;i<data.length;i++){
$scope.paged = data.data[i]; // response data
console.log($scope.paged+" $scope.paged");
}
.....
}
I get this in console:
{"status":"SUCCESS","data":[{"FirstName":"Student ","LastName":"1","Id":1,"ObjectState":0},{"FirstName":"Student ","LastName":"2","Id":2,"ObjectState":0}]}myData
No need to loop around in controller. Try the following:
Your Controller:
.controller("etudCtrl",["$scope", "$http", function ($scope, $http) {
$http({method: 'GET', url: 'MyURL'})
.success(function (data) {
$scope.currentPageStores= data.data;
console.log($scope.currentPageStores+ " values");
console.log("success");
}).error(function (data, status, headers, config) {
console.log("data error ...");
});
}])
Your student.html
<table>
<thead>...</thead>
<tbody data-ng-controller="etudCtrl">
<tr ng-repeat="store in currentPageStores track by $index" >
<td align="center">{{store.LastName}}</td>
<td align="center">{{store.FirstName}}</td>
</tbody>
</table>
Here is a PLUNKER example of how you access when the data comes in an array as yours : http://plnkr.co/edit/Q9ewbH7XevsOQG0Yzv6B?p=preview
You can't print a object on console with another string.
use
console.log(JSON.stringify($scope.currentPageStores)+" values");
or
console.log($scope.currentPageStores);
Is it possible to use a scope in a factory then using it on multiple controllers ?
I'm not really up to writing the same code in every controller, it'll be a pain to work on it ^^
Here's my current idea.
.factory('FactoryName', function($scope, $routeParams, $http) {
return {
search : function(str, http) {
var url = str+'.json';
return $http.get(url).success(http).error(function() {
alert('Unable to get back the data');
});
}
httpSuccessPaper : function(response) {
$scope.papers = response;
}
This way I only have this code once and all my controller are able to use the json of "reference". I could also write something like ng-repeat="p in papers" in some view.
Here is the way I call it in my controller :
.controller('CtrlName', ['$scope', '$routeParams', '$http', 'FactoryName'
function($scope, $routeParams, $http, FactoryName) {
FactoryName.search("Paper",FactoryName.httpSuccessPaper).then(function(){
$scope.paper = getByIdPa($scope.papers,$routeParams.id);
})
It seems a bit strange to me and I'm almost sure I'm trying something impossible.
I would like your opinion.
Thank you !
you can do it like this:
angular.module('apiServices', ['ngResource'])
.factory('ExampleService', ['$http', 'serviceUrl', function ($http, serviceUrl) {
return{
getInteractions: function () {
return $http({method: 'GET', url: serviceUrl + 'ctest', headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
},
getRoots: function () {
return $http({method: 'GET', url: serviceUrl + 'ntest', headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
},
getLogging: function (params) {
return $http.post(serviceUrl + 'atest', params);
},
getMessage: function (params) {
return $http({method: 'GET', url: serviceUrl + 'btest', params: params, headers: {'Cache-Control': 'no-cache, no-store', 'Pragma': 'no-cache', 'Expires': '0'}});
}
};
}]);
You don't want Services dealing with scopes. It's ok to repeat just the setting the scope part.
.factory('FactoryName', function($scope, $routeParams, $http) {
return {
search : function(str) {
var url = str+'.json';
return $http.get(url)
}
Then the controller:
.controller('CtrlName', ['$scope', '$routeParams', '$http', 'FactoryName'
function($scope, $routeParams, $http, FactoryName) {
FactoryName.search("Paper").then(function(papers){
$scope.paper = getByIdPa($papers,$routeParams.id);
})