ng-model is not working with ng-value in AngularJS - javascript

Below is my View page
<form name="form">
<label>Name</label>
<input name="name" type="text" ng-model='user.name' ng-value='emp.name' required />
<span ng-show="form.name.$touched && form.name.$invalid">Name is required</span>
<button ng-disabled="form.name.$touched && form.name.$invalid" ng-click='formUpdate()'>Update</button>
</form>
This is my controller
$scope.formUpdate = function() {
$scope.status = false;
$http({
method : 'POST',
url : 'model/update.php',
data : $scope.user ,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function mySuccess(response) {
$scope.update = response.data;
console.log(response.data);
}, function myError(response) {
$scope.update = response.statusText;
});
};
When I am using data: $scope.user in my HTTP call I am getting blank values on console but if I used data: $scope.emp, then I never get updated values of input fields rather getting old values of input fields.

ng-value binds the given expression to the value of the element.
As I understand your question, you are trying to initialize the input value to emp.name.
You should change your input to:
<input type="text" ng-model='user.name' ng-init='user.name = emp.name' required />
ng-init docs

try this code;
$scope.formUpdate = function(){
$scope.status = false;
$scope.$applyAsync();
$http({
method : 'POST',
url : 'model/update.php',
data : $scope.user ,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function mySuccess(response) {
$scope.update = response.data;
$scope.$applyAsync();
console.log(response.data);
}, function myError(response) {
$scope.update = response.statusText;
$scope.$applyAsync();
});
};

Related

How to create service and use it in controller

I am having a simple login form and I want to validate user upon successful HTTP request and it works fine. however, I've written all the code in the controller itself and I don't want that. i am new to angularjs so i have trouble creating service. so I need to create service for my logic. can anyone create service for the logic in the controller so that code works exactly same?
sample.html(for now it only prints username, password, and status code of response)
<html>
<head>
<script src="angular.js"></script>
<script src="angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="myapp">
<div ng-controller="mycontroller">
Username <input type="text" ng-model="login" /><br><br> Password <input
type="password" ng-model="pass" /><br>
<button type="submit" ng-click="myfunc()">Login</button>
<center>User name is {{ login }}, password is{{pass}}<br>
{{success.code}}
</div>
</body>
</div>
</body>
</html>
Controller
var app = angular.module("myapp", []);
app.controller("mycontroller", function($scope, $http, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
$http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: mydata
}).then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});
Super simple. First create a service, which injects $http module. Make a method you can call which returns promise from the $http module. In this example it's a get method.
app.service("ExampleService", function($http){
this.ExampleRequest = function(){
return $http.get('url');
}
});
Inject the service created above and you can call the functions you've defined in the service. Notice that the .then comes from the promise.
app.controller("exampleCtrl", function($scope, ExampleService){
$scope.onClick = function(){
ExampleService.ExampleRequest().then(function(data){
// Do something with data
});
}
});
Create a myService factory and create a function to send http req and return the response.
app.factory('myService', function($http) {
return {
httpReq: function(data) {
return $http({
method: 'POST',
url: "http://myapiurl.com/signin/",
headers: {
"authorization": "oauth mytoken",
'Access-Control-Allow-Origin': '*'
},
data: data
})
}
}
});
Now call it from the controller.
app.controller("mycontroller", function($scope, myService, $log) {
$scope.login = "";
$scope.pass = "";
$scope.myfunc = function() {
var obj = {
login_id: $scope.login,
password: $scope.pass
}
var mydata = JSON.stringify(obj);
myService.httpReq(mydata)
.then(function(response) {
console.log(response)
$scope.success = response.data;
},
function(reason) {
$scope.error = reason.data
console.log(reason);
$log.info(reason.data);
});
}
});

Angular: check value ng-blur

I'm trying to build a form in Angular, but i'm new with it, so I need some help :)
I have a field 'email' which should be checked when the user leave that field. A function in my controller should to check the entered value if it already exist in the database (ajax/http).
I found the 'ng-blur' function and have created a function in my controller to check the email. But, the $scope.user.email is undefined, and I don't known what i'm doing wrong. Can somebody help me?
This is my code so far:
HTML (jade)
p.claim-text Email
abbr.required.claim-text(title='required') *
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', value='', name='email', ng-model='user.email', ng-blur='checkEmail()' required)
p(ng-show="registerForm.email.$invalid && !registerForm.email.$pristine").help-block Invalid emailadres
p(ng-show="emailExists").help-block User exists! Click here to login
Controller function
$scope.checkEmail = function(){
console.log($scope.user.email);
$http({
method: 'GET',
url: '[someurl]',
data: $scope.user.email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}
Please try this snipped
var myApp = angular.module('myApp',[]);
myApp.controller('GreetingController', ['$scope','$http', function($scope, $http) {
//You can check POST at server side to get the entered email
$scope.checkEmail = function(email){
//REMOVE THIS LINE
console.log(email);return false;
$http({
method: 'POST',
url: '[someurl]',
data: email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<!--HTML -->
<div ng-app="myApp" ng-controller="GreetingController">
<input type="text" ng-blur="checkEmail(email)" ng-model="email"/>
</div>
OR
<!--JADE -->
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', name='email', ng-model='user.email', ng-blur='checkEmail(user.email)' ng-init="user.email=''" required)
You can pass the email to checkEmail function
input#billing_email.input-text.form-control.claim-input(type='email', placeholder='Email', value='', name='email', ng-model='user.email', ng-blur='checkEmail()' required)
Then in controller you just need to get the email from argument
$scope.checkEmail = function(){
console.log($scope.user.email);
$http({
method: 'GET',
url: '[someurl]',
data: $scope.user.email,
}).then(function successCallback(response){
//if response is true, set emailExists to true;
}, function errorCallback(response){
});
}

ng-model as initial input on form

I have an edit form that pushes data to a mongo db using express and angular. I am using ng-model for my data. The PUT works correctly to update the database. But I can't seem to make that found data as initial values on the input fields in my GET. I think I am binding things incorrectly. If that is the case, what am I doing wrong?
Thanks in advance.
My controller
app.controller('EditController', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
var self = this;
$http({
method: 'GET',
url: '/users/' + $routeParams.id,
data: $routeParams.id
}).then(function(response) {
// console.log(response.data);
self.id = $routeParams.id;
self.name = response.data.name;
self.age = response.data.age;
self.gender = response.data.gender;
self.img = response.data.img;
});
this.editForm = function() {
console.log('editForm');
console.log('Formdata: ', this.formdata);
$http({
method: 'PUT',
url: '/users/' + $routeParams.id,
data: this.formdata,
}).then(function(result) {
self.formdata = {}
});
} // end editForm
}]);
// end EditController
app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
$locationProvider.html5Mode({enabled:true});
$routeProvider.when('/', {
templateUrl: 'partials/match_partial.html'
}).when('/edit/:id', {
templateUrl: 'partials/edit_partial.html',
controller: 'EditController',
controllerAs: 'editctrl'
})
}]);
My HTML
<div>
<a ng-href="/">
<br>
<h3 class="back">Back to Match</h3>
</a>
<h1 class="editHeader">
Edit {{editctrl.name}}
</h1>
<form ng-submit="editctrl.editForm()">
<input type="text" ng-model="editctrl.formdata.id" placeholder="{{editctrl.id}}">
<input type="text" ng-model="editctrl.formdata.name" placeholder="{{editctrl.name}}">
<input type="text" ng-model="editctrl.formdata.age" placeholder="{{editctrl.age}}">
<input type="text" ng-model="editctrl.formdata.gender" placeholder="{{editctrl.gender}}">
<input type="text" ng-model="editctrl.formdata.img" placeholder="{{editctrl.img}}">
<input type="submit">
</form>
</div>
You can simply set the whole object to receive the response.data, this way:
$http({
method: 'GET',
url: '/users/' + $routeParams.id,
data: $routeParams.id
}).then(function(response) {
// console.log(response.data);
// Here
self.formdata = response.data;
});
And it will automatically fills all inputs with the object properties.

angular js: Error: $ is not defined in http post

I'm trying to post values from a form. Form has two fields- name and email. I have setup the controller as well but when i try to post, error is shown.
<form name="save" ng-submit="sap.saved(save.$valid)" novalidate>
<div class="form-group" >
<input type="text" name="name" id="name" ng-model="sap.name" />
</div>
<div class="form-group" >
<input type="email" name="email" id="email" ng-model="sap.email" />
</div>
<div class="form-actions">
<button type="submit" ng-disabled="save.$invalid || sap.dataLoading">Save</button>
</div>
</form>
My controller is:
(function() {
angular
.module('myApp.saved', [])
.controller('dataController', function($scope, $http) {
var sap = this;
$scope.post = {};
$scope.post.login = [];
$scope.sap = {};
$scope.index = '';
var url = 'save.php';
sap.saved = function(isValid)
{
if (isValid)
{
$http({
method: 'post',
url: url,
data: $.param({'user' : $scope.sap }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response)
{
// success
alert('success');
},
function(response)
{
// failed
alert('failed');
});
}
};
});
})();
When i submit, $ is not defined is shown. I'm pretty much new in angular. Can anyone tell what all mistakes I made?
$ is alias for jQuery and param is a jquery method.
Have you included jQuery?
data: $.param({'user' : $scope.sap }),
should be
data: {
'user': $scope.sap //POST parameters
}
data – {string|Object} – The response body transformed with the transform functions

Accessing Form elements and div from Angular Promise

I am learning angular js. I just want to clear the form fields and show a success div inside a http then().
this.formSubmitted = false;
this.successs = false;
myResumeApp.controller("FormController",['$http', function($http){
this.formSubmit = function(contactForm) {
this.formSubmitted = true;
if(contactForm.$valid)
{
$http({
method: 'post',
url: 'http://jerrythimothy.is-great.net/mailme.php',
data: $.param({
fname : this.fname,
email : this.email,
content : this.content
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
this.successs = true;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});// JavaScript Document
}
};
}]);
<div class="container" ng-controller="FormController as formCtrl">
<h2>Contact me</h2>
<div ng-show="formCtrl.successs" class="alert alert-success fade in" style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">Thank you for contacting me. I will be in touch with you shortly.</div>
<form role="form" name="contactForm" novalidate ng-submit="formCtrl.formSubmit(contactForm)">
Please let me know whether there is anything wrong with my code or any other suggestions. The control is coming inside the then() block. But I need to know how to access the successs element and clear the form fields.
Thank you.
Instead of this, use $scope (and add it to dependencies). Right know your successs property is assigned to different objects (window and callback function).
Controller code:
myResumeApp.controller("FormController",[
'$scope',
'$http',
function($scope, $http){
$scope.successs = false;
$scope.formSubmitted = false;
$scope.msg = {};
$scope.formSubmit = function(contactForm) {
$scope.formSubmitted = true;
if(contactForm.$valid)
{
$http({
method: 'post',
url: 'http://jerrythimothy.is-great.net/mailme.php',
data: $.param({
fname : $scope.msg.fname,
email : $scope.msg.email,
content : $scope.msg.content
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
$scope.successs = true;
$scope.msg = {};
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});// JavaScript Document
}
};
}
]);
HTML code:
<div class="container" ng-controller="FormController as formCtrl">
<h2>Contact me</h2>
<div ng-show="successs"
class="alert alert-success fade in"
style="padding-top:5px;padding-bottom:5px;margin-top:5px;margin-bottom:5px;">
Thank you for contacting me. I will be in touch with you shortly.
</div>
<form role="form" name="contactForm" novalidate ng-submit="formSubmit(contactForm)">
<input type="text" name="name" ng-model="msg.fname" />
<input type="text" name="email" ng-model="msg.email" />
<input type="text" name="content" ng-model="msg.content" />
<input type="submit" value="submit" />
</form>
You should be able to handle that in successCallback.
... .then(function successCallback(response) {
this.successs = true;
contactForm.reset()
}, ...
Also I don't think that this inside successCallback is same as in line where you initialize this.formSubmitted = false;...

Categories

Resources