Error in ajax call using angular js - angularjs

I am new to angular js .I tried making a small program that consists of ajax call using angular js $http .I guess I am some where wrong ,doing some mistake.
Would be happy If someone helps out. Following is code snippet
login.html
<head></head>
<body>
<form ng-app="" ng-controller="validateCtrl" name="myForm" novalidate>
<div ng-hide="var">
<h2><center>SIGN-IN</center></h2>
<p>Username:
<br>
<input type="text" name="user" ng-model="user" required><span style="color:red" ng-show="myForm.user.$error.required" />Username is required</p>
<p>Password:
<br>
<input type="password" name="password" ng-model="password" required /> <span style="color:red" ng-show="myForm.password.$error.required">Password is required.</span>
<p>
<input type="submit" ng-click="validate()" ng-disabled=" myForm.user.$invalid ||
myForm.password.$invalid" />
</p>
</div>
<div ng-hide="welcomeVar"> <span> {{ listOfCustomers }} </span>
<h2><center>Welcome! {{ user }}</center></h2>
<button class="list" ng-click="customerList()">List of Customers</button>
<ul>
<li ng-repeat="x in listOfCustomers">{{ x.CustomerID + ', ' + x.CompanyName }}</li>
</ul>
<br>
<button class="signout" ng-click="validate()">Log Out</button>
</div>
</form>
JS part:
<script>
function validateCtrl($scope, $http) {
$scope.user = 'ABC XYZ';
$scope.password = 'abcbc';
$scope.welcomeVar = true;
$scope.
var = false;
$scope.validate = function() {
$scope.
var = !$scope.
var;
$scope.welcomeVar = !$scope.welcomeVar
};
$scope.listOfCustomers = null;
$scope.customerList = function() {
$http.get("http://www.iNorthwind.com/Service1.svc/getAllCustomers")
.success(function(data) {
$scope.listOfCustomers = data;
})
.error(function(data) {
$scope.user = 'Xyz';
});
};
}
</script>

Your code is fine, except some syntax errors, but I hope it's because you tried to remove somrthing before posting code here ;)
Also the response for your request have this structure: {GetAllCustomersResult : [//here an array of elements]} , so, in success response handler you'll have to do: $scope.listOfCustomers = data.GetAllCustomersResult ;
But it's a minor things, the main issue described here:
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
To debug this, you had to open developer tools in any browser('F12' is common key to open it), and look in console and network requests.

Related

$broadcast is not working in Angularjs

I am using two controllers. When changes happen in one controllers it should get changed immediately in the other controller. I am using the $broadcast event to achive this.
My code:
My First controller
app.controller('configurationCtrl', function($scope, $http,Notification,$rootScope,$cookies) {
$scope.awssubmit=function(){
$scope.page_loader=true
$http.post("/insert_config_details",$scope.userdata).then(function(List){
if(List){
$scope.page_loader=false;
$cookies.put("bucket",$scope.userdata.bucket_name)
$scope.$broadcast('eventEmitedName', 'Some data');
Notification.success('<span class="glyphicon glyphicon-ok"></span> <strong>AWS Configuration details updated successfully.</strong>');
}
else{
$scope.page_loader=false;
Notification.error('<span class="glyphicon glyphicon-ok"></span> <strong>Error!!! Please try again later.</strong>');
}
$scope.awssave = false;
$scope.awstext=true;
})
}
});
My Second Controller:
app.controller('SidemenuController', function($scope, $http,$location,BucketService)
{
$scope.$on('eventEmitedName', function (event, data) {
console.log("Called"); //I am not getting this
value
console.log(data); // 'Some data' // I am not getting this
value
});
});
aws_submit() is called from my view and everything seems to work fine. But in SidemenuController I am not getting any data. Is there any mistake in my code?
Update:
My view :
<form id="awsform" method="post" name="awsform" class="form-horizontal" novalidate>
<div class="col-sm-6 four_module_config">
<div class="account_settings">
<div class="col-sm-12 heading_config" ng-hide="awssave">
<h4 class="sub_title col-sm-11" style="border-bottom:none">AWS S3 Configurations</h4>
<% if(valid_role[1]) { %>
<div class="action col-sm-1">
<span class="actico editrole" ng-click="editaws()">
<a href='javascript:void(0)' ></a>
</span>
</div>
<% } %>
</div>
<div class="col-sm-12 heading_config" ng-show="awssave">
<h4 class="sub_title col-sm-9" style="border-bottom:none">AWS S3 Configurations</h4>
<div class="action col-sm-3 close_config">
<button type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-show="awstest"
ng-click="verifyaws()">Test</button>
<button type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-show="submitawssave"
ng-click="awssubmit()">Submit</button>
<button type="button" class="site_btn submit_btn save_config col-sm-2" id="submit" ng-click="closeaws()">Cancel</button>
</div>
</div>
<div class="ipfield col-md-8 hint_txt_conf">
*Enter your AWS access Key, S3 Bucket name configured in your AWS Environment. Which is used to store your document in the
cloud.
</div>
<div class="ipfield first_ipfield">
<div class="col-md-8">
<label for="name" class="usrlabel">AWS access key <span class="mandat">*</span></label>
<input type="password" ng-disabled="awstext" ng-model="userdata.key" required name="key" class="txt_box" id="key" placeholder="Enter AWS access key">
<span toggle="#key" class="fa fa-fw fa-eye field_icon toggle-password"></span>
</div>
</div>
<div class="ipfield">
<div class="col-md-8">
<label for="name" class="usrlabel">AWS Secret Key <span class="mandat">*</span></label>
<input type="password" ng-disabled="awstext" ng-model="userdata.secretkey" required name="secretkey" class="txt_box" id="secretkey" placeholder="Enter AWS Secret Key">
<span toggle="#secretkey" class="fa fa-fw fa-eye field_icon toggle-password"></span>
</div>
</div>
<div class="ipfield">
<div class="col-md-8">
<label for="name" class="usrlabel">AWS Region Code <span class="mandat">*</span></label>
<input type="text" ng-disabled="awstext" ng-model="userdata.region" required name="region" class="txt_box" id="region" placeholder="Enter AWS Region Code">
</div>
</div>
<div class="ipfield">
<div class="col-md-8">
<label for="name" class="usrlabel">AWS Bucket Name <span class="mandat">*</span></label>
<input type="text" ng-disabled="awstext" ng-model="userdata.bucket_name" required name="bucket_name" class="txt_box" id="bucket"
placeholder="Enter AWS Bucket Name">
</div>
</div>
</div>
</div>
</form>
If you want to send data from one controller to another controller using $brodcast than use $rootscope.$broadcast
$rootScope.$broadcast('eventEmitedName', 'Some data');
Second Controller
app.controller('SidemenuController', function($scope, $http,$location,BucketService) {
$scope.$on('eventEmitedName', function (event, data) {
console.log("Called");
console.log(data); // 'Some data'
$scope.bucket = data;
});
});
Note: Do not use $rootscope.$on as listener because $rootscope
listener are not destroyed . Instead it will create listeners stack
If you want to call one controller event into another there are four methods available:
$rootScope.$broadcast() if your controller are not in a parent / child relation.
If your second controller (event fired here) is a parent you can use $scope.$broadcast();
If your second controller (event fired here) is a child you can use $scope.$emit();
The best way to solve this would be to use a service -> Example of using a service to share data between controllers.
Note: You need to destroy $rootScope.$on() listeners manually avoid stacking events. This Difference between $rootScope.$on vs $scope.$on and this Do you need to unbind $scope.$on in $scope $destroy event? will help you understand the basics of using events.
View
<div ng-controller="MyCtrl">
<button ng-click="broadcast()">
broadcast
</button>
</div>
<div ng-controller="MySecondCtrl">
{{ test }}
</div>
AngularJS application
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', function($scope, $rootScope) {
$scope.broadcast = function() {
$rootScope.$broadcast('test', 'testit');
}
});
myApp.controller('MySecondCtrl', function($scope, $rootScope) {
var registerScope = $rootScope.$on('test', function(test, args) {
console.log(args);
$scope.test = args;
});
// clean up, destroy event when controller get destroyed.
$scope.$on('$destroy', registerScope);
});
> demo fiddle

AngularJS 1.x: Dynamically created multiple File Upload fields

You have to excuse me, I do not use Angular that often. I need to implement a solution in which I can upload files from dynamically generated input fields.
The catch is that I cannot use any directives (this is due to the framework I am using in which AngularJS is implemented).
My current code for creating fields:
$scope.addNewFile = function() {
var newFileNo = $scope.files.length + 1;
$scope.files.push({'id': 'file' + newFileNo});
};
$scope.removeFile = function() {
var lastFile = $scope.files.length - 1;
$scope.files.splice(lastFile);
};
And here is the code for uploading files (not correct, because of static id and name values:
$scope.uploadFile = function() {
var file = document.getElementById('file').files[0],
r = new FileReader;
r.onloadend = function (e) {
var data = e.target.result;
console.log('data');
console.log(data);
// http.post
};
r.readAsArrayBuffer(file);
};
And here is my HTML:
<div data-ng-repeat="file in files">
<div class="row top-buffer">
<div class="col-lg-10">
<input type="file"
ng-model="file.name"
name="file"
class="form-control"
id="file">
</div>
<div class="col-lg-2 text-right">
<div class="btn btn-primary" ng-click="uploadFile()">Upload</div>
</div>
</div>
</div>
<div class="row top-buffer">
<div class="col-lg-11"></div>
<div class="col-lg-1 text-right">
<div class="glyphicon glyphicon-plus" aria-hidden="true" ng-click="addNewFile()"></div>
<div class="glyphicon glyphicon-minus" aria-hidden="true" ng-click="removeFile()"></div>
</div>
</div>
I can't really understand how I can get the values of dynamically generated file fields... any help appreciated!
There is no ng-model for <input type=file, but you can achieve what you want setting the id dynamically with ng-attr:
<div ng-repeat="file in files">
{{file.id}}:
<input type="file"
ng-attr-name="{{file.id}}"
ng-attr-id="{{file.id}}">
</div>
On uploadFile() you can post them:
$scope.uploadFile = function() {
$scope.files.forEach(function(file) {
// $http.post: document.getElementById(file.id).files[0])
});
};
Example on Fiddle: https://jsfiddle.net/virgilioafonsojr/92nw4j4f/1/
I hope it helps.
Writing an uploader properly is a very difficult task. A major problem with an upload component/directive is getting it to work in Internet Explorer; because it can only be used once in IE. Another problem is that IE will not let you programmatically "press" the button, it must be a real mouse click.
There are upload libraries out there for AngularJs, just google. However if you are intent on doing it yourself then you can use my git repo as an example of how it should be done. Just use the jwtUploader and jwtUploaderButton directives.
https://github.com/smylydon/SEPE-7WCM0033-0206-FRONTEND/tree/master/client/app

posting data through angular form without page reload in angular

$scope.createPermission= function(form){
AppFactory.createNewPermission(form)
.success(function(data) {
$scope.updatedPermissions = data;
$scope.navMode='getPermission'
var original = $scope.permission;
$scope.reset(original);
$scope.permission = {}; // clear the form
})
.error(function(data) {
console.log('Error in creating permission: ' + data);
});
$scope.Execute=function(id) {
if($scope.navMode=='updatePermission') {
$scope.editPermission(id);
} else if($scope.navMode=='createPermission') {
$scope.createPermission($scope.permission);
}
}
}
$scope.reset= function(original) {
$scope.permission= angular.copy(original)
$scope.form2.$setPristine(true);
//$scope.form2.$setUntouched(true);
}
HTML:
<div class="row">
<div class="container col-sm-6 col-sm-offset-2"
ng-show="navMode == 'createPermission' || navMode=='updatePermission' || navMode=='getPermission'">
<div>
<h1>Permissions</h1>
</div>
</div>
<form class="form2" ng-show="showHide('Create')" ng-if=""name="form2" ng-submit="Execute(permissionId)" novalidate>
<div class="form-group" ng-class="{ 'has-success': form2.name.$valid && submitted, 'has-error': form2.name.$invalid && submitted }">
<label>Permission Name</label>
<input type="text" name="name" class="form-control" ng-model="permission.name" required/>
<p class="help-block" ng-show="form2.name.$error.required && submitted">
A permission name is required
</p>
</div>
<div class="row col-lg-offset-3">
<button class="btn btn-primary" ng-disabled="form2.$invalid" type="submit">Save</button>
</div>
</form>
</div>
I have above piece of code in controller and is executed on submission of the form. Now , It does work fine on page reload but I can not add data through form back to back. I need to reload teh page everytime to post new data through the form.
Why exactly is that ?
How do I fix this?
Without seeing the HTML part of this, I would guess you are using the action attribute of <form>. AngularJS provides ng-submit which allows you to set a handler for the submit event, without actually 'submitting' the form in the traditional sense. See https://docs.angularjs.org/api/ng/directive/ngSubmit.

Cannot read property $valid of undefined

I have a form like this -
<form name="myForm" novalidate>
There are some fields in the form which I am validating and then submitting the form like this -
<input type="button" ng-click="Save(data)" value="Save">
In the controller, I want to check if the form is not valid then Save() should show some error on the page. For that, I am setting up a watch like this -
$scope.$watch('myForm.$valid', function(validity) {
if(validity == false)
// show errors
});
But I am always getting this error on running it -
Cannot read property '$valid' of undefined
Can someone explain why?
Thanks
You just misspelled "myForm" in your controller code. In order to remove the error, Write "myform" instead of "myForm".
However I expect what you want is like this.
$scope.Save = function(data){
alert($scope.myform.$valid);
}
I setup jsfiddle.
In my case I was wrapping the form in a modal created in the controller and therefore got the same error. I fixed it with:
HTML
<form name="form.editAddress" ng-submit="save()">
<div class="form-group">
<label for="street">Street</label>
<input name="street" type="text" class="form-control" id="street" placeholder="Street..." ng-model="Address.Street" required ng-minlength="2" />
<div class="error" ng-show="form.editAddress.street.$invalid">
<!-- errors... -->
</div>
</div>
<button type="submit" class="btn btn-primary" >Save address</button>
</form>
JS
angular.module("app").controller("addressController", function ($scope, $uibModal, service) {
$scope.Address = {};
$scope.form = {};
$scope.save = function() {
if (modalInstance !== null) {
if (isValidForm()) {
modalInstance.close($scope.Address);
}
}
};
var isValidForm = function () {
return $scope.form.editAddress.$valid;
}
});

Angular JS Doesnt Seem to work, newbie

i got one sample app from net, which i tried to implement, but it doesn't seem to work, below is the code of app, please help me by fixing it and suggest me how can i make it more better. i am a newbie to Angular.
Jsfiddle : http://jsfiddle.net/eGzZg/
<div id="main" ng-controller="contactDetails">
<label>Name</label>
<input type="text" name="name" ng-model="newcontact.name"/>
<label>Email</label>
<input type="text" name="email" ng-model="newcontact.email"/>
<label>Phone No</label>
<input type="text" name="phno" ng-model="newcontact.phno"/>
<input type="hidden" ng-model="newcontact.id" />
<input type="button" value="Save" ng-click="saveContact()" />
<div id="table">
<div id="thead">
<span>Name</span>
<span>Email</span>
<span>Phone No</span>
<span>Action</span>
</div>
<div id="tbody" ng-repeat="contact in contacts">
<span> {{contact.name}} </span>
<span> {{contact.email}} </span>
<span> {{contact.phno}} </span>
<span> Edit</span>
<span> Delete</span>
</div>
</div>
</div>
<script>
var uid = 0;
function contactDetails($scope) {
//$scope.contacts = [{ id : null, 'name':null, 'phno':null }];
$scope.contacts = [
{ id:0, 'name': 'Viral',
'email':'hello#gmail.com',
'phno': '123-2343-44'
}
];
$scope.saveContact = function(){
alert('sd');
for( i in $scope.contacts){
if($scope.contacts[i].id == $scope.newcontact.id || ($scope.contacts[i].name == $scope.newcontact.name && $scope.contacts[i].phno == $scope.newcontact.phno)){
$scope.contacts[i] = $scope.newcontact;
}else{
$scope.contacts.id = ++uid;
$scope.contacts.push($scope.newcontact);
}
$scope.newcontact = {};
}
}
}
</script>
don't forget to actually include angular and also you forgot ng-app
<body ng-app>
here ya go
Just change $scope.contacts = [{ id : null, 'name':null, 'phno':null }];
to $scope.contacts = [];
Even if you set the properties of the contact elements to null, it still has a single element and thats why there is no text, but the buttons are appearing when the page is loaded.

Resources