ng-model as initial input on form - javascript

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.

Related

AngularJS factory and controller code, not producing anything

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

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);
});
}
});

Values in $scope are not visible after location.path

I am facing problem while building a single page app with angularjs. My app has a login page. If authentication is success, app is routed to home page in which some data is displayed from $scope. However, no data is being displayed after login.
I am using location.path to route to home when sign in successful. For reference, I am trying to print "$scope.homePageDetails" in home.html but nothing is getting printed. Can someone say, what wrong am I doing and how can I resolve this issue?
index.html file:
<html>
<body>
<nav>
<ul>
<li ng-hide="isUserLoggedIn"> <span class="glyphicon glyphicon-log-in"></span> Login</li>
</ul>
</nav>
<div ng-view></div>
</body>
</html>
login.html file:
<div>
<form class="form-signin">
<input type="text" class="form-control" placeholder="Email" ng-model="userDetails.userName" required autofocus>
<input type="password" class="form-control" placeholder="Password" ng-model="userDetails.Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" ng-click="signIn()">
Sign in</button>
</form>
home.html:
<p> {{homePageDetails}}</p>
angular module and controller:
app.controller('myCtrl', ['$scope','$http', '$location' function($scope,$uibModal,$http, $location, $window) {
$scope.signIn = function(){
$http({
url: "http://localhost:3050/postSignIn",
method: "POST",
headers: {'Content-Type': 'application/json; charset=utf-8'
},
data: $scope.userDetails
})
.then(function(response){
console.log('resp is',response);
$scope.isUserLoggedIn = true;
$location.path('/home');
$http({
url: "http://localhost:3050/getHomePageDetails",
method: "GET",
headers: {'Content-Type': 'application/json; charset=utf-8'
}
})
.then(function(response){
$scope.homePageDetails = response.data.slice(0);
}, function(response){
// failure callback
console.log('failure in getting homePageDetails',response);
});
},
function(response){
// failure callback
console.log('failure is',response);
});
}
}]);
module:
var app = angular.module('myApp', ['ngRoute']);
router:
app.config(function ($routeProvider, $locationProvider, $httpProvider) {
$routeProvider.when('/home',
{
templateUrl: 'home.html',
controller: 'myCtrl'
});
}
You can try this
$routeProvider
.when('/home',
{
templateUrl: 'home.html',
controller: 'myCtrl'
})
.when('/login',
{
templateUrl:'login.html',
controller:'myCtrl'
})

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

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();
});
};

data not getting populated to the view from controller after routing in angular

I am seeing no data in my view (Html) . where as i am getting data into controller from service as well.
Please let me know what i am missing .
Any suggestions what i am missing
Controller:
(function () {
'use strict';
angular.module('app') .controller('UserController', UserController);
UserController.$inject = ['$scope', 'UserService', '$http', '$filter', '$rootScope','$location','$window'];
function UserController($scope, UserService, $http, $filter, $rootScope,$location,$window) {
$scope.editUser = function(userDetails){
UserService.editUser(userDetails).then(editUserSuccess,editUserFailure);
$location.path('edit');
}
var editUserFailure =function (error){
};
var editUserSuccess = function (response) {
var userRow = response.data;
$scope.edituserData=userRow;
};
};
})();
This is my service part
(function () {
'use strict';
angular.module('app').factory('UserService', UserService);
UserService.$inject = ['$http', '$rootScope'];
function UserService($http, $rootScope) {
var service = {};
service.editUser = editUser;
return service;
function editUser(editUserObj){
console.log(editUserObj.userId);
return $http({
method: 'POST',
url: 'editUser',
data: btoa(editUserObj.userId),
contentType: "application/json; charset=utf-8",
});
}
}
})();
My routing from application
appname.config(function($routeProvider) {
$routeProvider
.when("/edit", {
templateUrl:"my.html",
controller : 'UserController'
});
});
my.html:
--------
When i am trying to get data in my html template
<div class="row">
<div class="col-lg-6 col-sm-6 col-xs-6">
<p class="text-right"><strong>Middle Name :</strong></p>
</div>
<div class="col-lg-6 col-sm-6 col-xs-6">
<p class="text-left-user"> {{editUserData.screenName}}</p>
</div>
</div>
Thanks in advance
Your service just needs to return the data on success. Right now it is only returning the Promise.
(function () {
'use strict';
angular.module('app').factory('UserService', UserService);
UserService.$inject = ['$http', '$rootScope'];
function UserService($http, $rootScope) {
var service = {};
service.editUser = editUser;
return service;
function editUser(editUserObj){
console.log(editUserObj.userId);
return $http({
method: 'POST',
url: 'editUser',
data: btoa(editUserObj.userId),
contentType: "application/json; charset=utf-8",
}).success(function(response){
return response;
});
}
}
})();
Then in your .then success function in the controller, you should have the response available.

Categories

Resources