I am using AngularJS. I want to post the data in a file in JSON format to the localhost server i.e. http://localhost:8080/out.json.
How should the post method should be implement for this scenario ? OR Any other working example for the post method which are able to save the data in the json format is helpful.
Thanks.
Here is my code :
var app = angular.module('myApp', []);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.controller('FormCtrl', function ($scope, $http) {
$scope.data = {
firstname: "default"
};
$scope.submitForm=function($scope, $http) {
$http.post('someurl', JSON.stringify(data)).
success(function(data) {
console.log(data);
}).
error(function(data) {
console.log(data);
});
};
});
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="controller.js"></script>
</head>
<body>
<div ng-controller="FormCtrl">
<form name="saveTemplateData" action="#">
First name: <input type="text" ng-model="data.firstname"> <br/><br/>
<button type="submit" ng-Click='submitForm()'>Submit</button>
</form>
</div>
</body>
</html>
Adding my comment as an answer:
Sounds like you're sending to a different domain than the one you're on.. in general you can't do that unless that domain accepts such requests.
You doesn't need to use the stringily function.
I think you forgot to put $scope. before data
try with this code :
$scope.submitForm=function($scope, $http) {
$http.post('someurl', $scope.data).
success(function(data) {
console.log(data);
}).
error(function(data) {
console.log(data);
});
};
EDIT
Oh I didn't see that but you don't need too specify $scope, $http again when you declare a function like submitForm. If you do it, you will have to variable named $scope which not will be in the same scope and you haven't access to data.
$scope.submitForm = function() {
$http.post('someurl', $scope.data).
success(function(data) {
console.log("success" + data);
}).
error(function(data) {
console.log("error" + data);
});
};
Related
I seem to be facing a problem with sharing data between controllers in angularjs
I have two HTML files, one controller for each of them, a service to share Information and a regular app file for routing.
Here's the first file
<div class="container">
<button ng-click="broadcastData()"> Send </button> </div>
Here's the corresponding Controller for it:
angular.module('myApp').controller('sendInfoController',
['$scope','$rootScope','$location'
function ($scope,$rootScope, $location)
{
$scope.broadcastData=function()
{
shareInfoService.sendData({info: "Okay"});
$location.path('/infoView');
}
}]);
Here's the second HTML File: (infoView.html)
<div>
{{data}}
</div>
Here's the corresponding controller for it:
angular.module('myApp').controller('infoController',
['$scope','$rootScope',
function ($scope,$rootScope)
{
$scope.data="hello";
$rootScope.$on('sendTheData', function(event,args)
{
console.log(args);
$scope.data=args.info;
});
console.log($scope.data);
}]);
Here's the service to share information:
angular.module('prkApp').factory('shareInfoService',
['$rootScope',
function ($rootScope) {
//Return the particular function
return ({
sendData: sendData
});
function sendData(data)
{
$rootScope.$broadcast('sendTheData', data);
};
}]);
When I click on the button in the first HTML File, the location gets changed to infoView and the shareInfoService.broadcastData function gets called.
It redirects to the second HTML File. However, the information that is displayed on this page is "hello" and not "Okay".
The web console logs shows
{info: "Okay"}
first and "hello" immediately after that.
How can it be rectified so as to show the data that is sent by the previous controller?
You are sending out the broadcast before you change the location so the listener in the infoController will not be loaded when the event is broadcasted. Instead of broadcasting, you can store the value in the service and then have infoController retrieve it when it loads.
Service
angular.module('prkApp').factory('shareInfoService', ['$rootScope', function($rootScope) {
var data;
//Return the particular function
return ({
sendData: sendData,
getData: getData
});
function sendData(new_data) {
data = new_data;
};
function getData() {
return data;
}
}
]);
Controller
angular.module('myApp').controller('infoController', ['$scope', '$rootScope', function($scope, $rootScope) {
$scope.data = "hello";
console.log($scope.data);
$scope.data = shareInfoService.getData();
console.log($scope.data);
}
]);
Am pretty new to AngularJS.
I have written a code and its working fine.
Would like to know, is there a way to further shrink the controller.
My index.html file is
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<input type="text" ng-model="sea" ng-change="newSearch()"/>
<ul>
<li ng-repeat="x in myData">
{{ x.name + ', ' + x.emailid}}
</li>
</ul>
</div>
<script src="js/app.js"></script>
<script src="js/controllers/maincontroller.js"></script>
</body>
</html>
And maincontroller.js is
app.controller('customersCtrl', function($scope, $http) {
$http(
{
url: "http://localhost:8080/cordovaprojects/123m/www/customer.php",
method: "GET",
params: {'name':'powercom'}
})
.then(function(response) {
$scope.myData = response.data.records;
});
$scope.newSearch = function() {
$scope.newSea = $scope.sea;
$http(
{
url: "http://localhost:8080/cordovaprojects/123m/www/customer.php",
method: "GET",
params: {'name':$scope.newSea}
})
.then(function(response) {
$scope.myData = response.data.records;
});
};
});
If you notice I have used the same $http function twice with a difference of param.
Thank you.
As #maurycy noted in his comment, the way to keep the size of your controllers small is to keep commonly used functionality inside of a service. Consider this service:
app.service('Customers',
[ '$http',
function($http) {
return {
byName: byName
};
function byName(name) {
return $http({
url: "http://localhost:8080/cordovaprojects/123m/www/customer.php",
method: "GET",
params: {'name': name}
});
}
}
]
);
You can then use this service in a controller like this:
app.controller('customersCtrl', [
'$scope', 'Customers',
function($scope, Customers) {
$scope.myData = null;
Customers.byName('powercom')
.then(function(response) {
$scope.myData = response;
});
}
]);
Which is quite a bit shorter than what you have now, plus it is separated making it able to be used in any other part of your application (as well as much easier to test). If the endpoint changes, you have only a single spot to change and, since it's used everywhere else already, you're done.
Update
To bind on an ng-click, I'll assume you have an input bound to a local model, as well as a button for which to act as the click target, something like this:
<input type="text" data-ng-model="customerName" />
<button data-ng-click="lookupCustomer()">
Lookup Customer
</button>
Then in your controller, you can define the lookupCustomer function this way:
app.controller('customersCtrl', [
'$scope', 'Customers',
function($scope, Customers) {
$scope.customerName = 'powercom';
$scope.lookupCustomer = lookupCustomer;
$scope.myData = null;
lookupCustomer();
function lookupCustomer() {
Customers.byName($scope.customerName)
.then(function(data) {
// Do something with data
});
}
}
]);
You can add checks inside of lookupCustomer to guard against edge cases (no need to lookup an empty customer name), but this should work for you.
It'll be better if you'll create the service for getting your data.
app.service('dataService', function($http) {
this.get = function get(param) {
return $http({
url: "http://localhost:8080/cordovaprojects/123m/www/customer.php",
method: "GET",
params: {'name': param}
});
}
});
app.controller('customersCtrl', function($scope, dataService) {
dataService.get('powercom').then(function(response) {
$scope.myData = response.data.records
});
$scope.newSearch = function() {
$scope.newSea = $scope.sea;
dataService.get($scope.newSea).then(function(response) {
$scope.myData = response.data.records
});
};
});
And also is not necessary to create a functions in your $scope. You can use "this" and get access for your data in controller by controller name or alias like this:
<div ng-controller="customersController as ctrl"><p ng-click="ctrl.newSearch">Hello</p></div>
I am trying to put my service file in another js file but getting error
Unknown provider: $scopeProvider <- $scope <- getData
I have created 3 files which are :
app.js
app=angular.module('myApp', []); console.log("app.js loaded.");
service.js
app.service('getData',['$scope','$http',function($scope,$http){
this.getDataFrom = function(){
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {$scope.names = response.records;});
}; }]); console.log("script loaded.");
index.html
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script><script src="app.js"></script><script src="service.js"></script>
<script>app.controller('customersCtrl',['$scope','getData', function($scope, getData) {
alert(getData.getDataFrom());}]);</script>
Basically i am trying to put this code in different files.
You can't inject scope into services. It doesn't work like that, since they aren't associated with a scope.
Try rewriting your code as follows:
Remove the $scope reference in the service and the injection, and return the result of the $http.get, which is a promise
app.service('getData',['$http',function($http){
this.getDataFrom = function(){
return $http.get("http://www.w3schools.com/angular/customers.php")
}; }]); console.log("script loaded.");
Then, change your controller to use the service, and when the data is fetched, to update its scope:
<script>app.controller('customersCtrl',['$scope','getData','commentDataService', function($scope, getData,commentDataService) {
commentDataService.getComments().then(function(data) {
$scope.data = data;
console.log('the data is here!', data);
});
alert(commentDataService.getComments());
alert(getData.getDataFrom());}]);</script>
You cannot have a $scope injected in the service. So your service should look like below:
app.service('getData',['$http',function($http){
var names = null;
this.getDataFrom = function(){
$http.get("http://www.w3schools.com/angular/customers.php")
.success(function(response) {names = response.data.records; return names;});
}; }]);
I got it worked and to fetch data by help of this info "$scope is not associated with a scope"
finally obtained data with this code :
service.js
app.service('getData',['$http',function($http){
this.getDataFrom = function(){
return $http.get("http://www.w3schools.com/angular/customers.php")
.then(function(response) {
return response.data.records;
});
};}]);
index.html
app.controller('customersCtrl', ['$scope', 'getData', function($scope, getData) {
getData.getDataFrom().then(function(response){
alert(JSON.stringify(response));
$scope.names=response;
});
}]);
===========================================================================
Update 1
Fixed code produce new error of
ReferenceError: inputName is not defined
on the line of
inputName:inputName,
Below is the new code
<script src="/library/angularjs/1.2.0-rc.3/angularjs.js"></script>
<script src="/library/angularjs/1.2.0-rc.3/angular-route.js"></script>
<script src="/library/angularjs/1.2.0-rc.3/angular-resource.js"></script>
<script>
var app= angular.module('myApp', ['ngRoute', 'ngResource']);
app.factory('Greeter', ['$resource',function($resource){
return $resource(
'http://123.com/processor.php',
{
inputName:inputName,
callback: 'JSON_CALLBACK'
},
{
query: {method:'GET',isArray:true}
});
}]);
app
.controller('MyCtrl', ['$scope', 'Greeter',
function($scope,Greeter){
/*alert("yes");*/
$scope.greet = function(){
//alert("greetttt");
alert("before greeeter"+$scope.inputName);
Greeter.query(
{inputName:$scope.inputName},
function(response){
alert(response[0].myCodeId);
$scope.output=response[0].myCodeId;
}
);
};
}]);
</script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
Your name:
<input type="text" ng-model="inputName" name="myInput" value="World"/>
<button ng-click="greet()">greet</button>
<div>
Test Output Here
{{output}}
</div>
</div>
</div>
I wonder where do I get it wrong?
Thanks
http://plnkr.co/edit/CKgWrson3IbMugRKdX5p?p=preview
A few problems that I fixed that others pointed out in the comment.
Remove $scope from factory. Here you are getting a generic $scope object but not the actual scope. You will get that in the controller.
When you call angular resource with query() the first argument is already the param. But you can specify the common params like you did before.
function($resource) {
return $resource('mocked-resource.json', {
callback: 'JSON_CALLBACK'
}, {
query: {
method: 'GET',
isArray: true
}
});
Hope this helps.
inputName:inputName,
second inputName refer to not existing variable. I think this line can be removed at all. But it depends on what you want to achieve.
I would like to use i18n and i10n in my Angular app.
I read that Angular-translate can help with this, however, it doesn't work for me.
In my index.html:
<!DOCTYPE html>
<html ng-app="eApp">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="../common/css/bootstrap.css" />
<link rel="stylesheet" type="text/css" href="../common/css/style.css" />
<title></title>
</head>
<body ng-controller="AppCtrl">
<div id="container" ng-view></div>
<!--- Libs Js files --->
<script type="text/javascript" src="../vendor/angularjs/angular.min.js"></script>
<script type="text/javascript" src="../vendor/angularjs/angular-route.min.js"></script>
<script type="text/javascript" src="../vendor/angularjs/angular-translate.min.js"></script>
</body>
</html>
In my eApp.js:
var eApp = angular.module('elbitApp', ['ngRoute', 'ui.bootstrap', 'config', 'pascalprecht.translate']);
// configure our routes
eApp.config(["$routeProvider",
function ($routeProvider) {
$routeProvider
// route for the home page
.when('/c', {
templateUrl: 'c/partials/c.html',
controller: 'CController'
})
// route for the about page
.when('/de', {
templateUrl: 'd/partials/dE.html',
controller: 'DEController',
resolve: {
data: function (DDataService) {
return DDataService.loadData().then(function (response) {
return response.data;
});
}
}
})
// route for the contact page
.when('/di', {
templateUrl: 'd/partials/di.html',
controller: 'DIController',
resolve: {
data: function (DDataService) {
return DDataService.loadData().then(function (response) {
return response.data;
});
}
}
}).otherwise({
redirectTo: '/di'
});
}]).config(["$httpProvider",
function ($httpProvider) {
// Configure the $httpProvider to parse date with date transformer
$httpProvider.defaults.transformResponse.push(function (responseData) {
convertDateStringsToDates(responseData);
return responseData;
});
}]).config(["$translateProvider",
function ($translateProvider) {
$translateProvider.translations('en', {
"TITLE": 'Hello',
"FOO": 'This is a paragraph.',
"BUTTON_LANG_EN": 'english',
"BUTTON_LANG_DE": 'german'
});
$translateProvider.translations('de', {
"TITLE": 'Hallo',
"FOO": 'Dies ist ein Paragraph.',
"BUTTON_LANG_EN": 'englisch',
"BUTTON_LANG_DE": 'deutsch'
});
$translateProvider.preferredLanguage('en');
}]);
// main controller that catches resolving issues of the other controllers
eApp.controller('AppCtrl', function ($rootScope) {
$rootScope.$on("$routeChangeError", function (event, current, previous, rejection) {
alert("Cant resolve the request of the controller "); //TODO: add URL + additional data.
})
});
In this file I defined my app and added the $translateProvider and two dictionaries.
Afterwards I got to my deController.js:
eApp.controller('DispatcherEventsController', ['$scope', '$route', '$translate',
function($scope, $route, $translate){
var data = $route.current.locals.data;
$scope.title = $translate.instant("FOO");
$scope.switchLanguage = function(languageKey){
$translate.use(languageKey);
};
}]);
In de.html I added a h1 tag with FOO and in a click I would like to change to German:
<h1>{{title |translate}}</h1>
<h1 translate="{{title}}"></h1>
<button type="button" id="searchButton" class="btn btn-default" ng-click="switchLanguage('de')">German</button>
I don't get any problem, but nothing happens. I expected that the English title will be converted to German title.
What can I do to make this work?
It works well for me. Here is a jsFiddle DEMO.
In this case, you want to bind $scope.title with translation key "FOO".
You should change the value of $scope.title dynamically in the switchLanguage function. Then view will be updated accordingly.
//default value
$scope.title = $translate.instant("HEADLINE");
$scope.switchLanguage = function(key){
$translate.use(key);
$scope.title = $translate.instant("HEADLINE");
}
In my opinion, maybe use translation key is a better way than scope data binding. You don't have to maitain the value of key manually.
<h1>{{'FOO' | translate}}</h1>
According to the error msg you provided, maybe you could check if there is any typo syntax in your controller.
Should be
$translate.use(languageKey)
Not
$translate.uses(languageKey)
Though not directly related to your question - you must remember to set the preferred language in the translations.js file, or whatever its name is that you define your key-value translations. Otherwise it will just default to whatever the key is.
...
GREETING: 'Hello World!',
...
$translateProvider.preferredLanguage('en');
Without this line, when doing this:
<h2>{{'GREETING'|translate}}</h2>
Would appear as just GREETING instead of the 'Hello World.'