not able to call $http in angularjs - javascript

I want to call a service through http for a dropdown list in angularjs. But, the function is not going to execute the http service method.
im binding the dropdown list by ajax call , after binding the ajax call i would like to show the details of the selected value from ajax call.
<script type="text/javascript">
var app = angular.module('myApp', [])
app.controller('myCtrl', function ($scope, $http, $window) {
$scope.DefaultLabel = "Loading.....";
var post = $http({
method: "POST",
url: "/PIRDetails/AjaxMethod",
dataType: 'json',
data: {},
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
$scope.DefaultLabel = "Please Select PIR Device";
$scope.Customers = data;
});
post.error(function (data, status) {
$window.alert(data.Message);
});
$scope.getPIRData = function (id) {
$http.get("/PIRDetails/GetPIRStatus/e203")
.then(function (response) {
$scope.myWelcome = response.data;
});
};
});
</script>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="form-control" onchange="getPIRData(this.value);">
<option value="0" label="{{DefaultLabel}}"></option>
<option ng-repeat="customer in Customers" value="{{customer.Value}}">{{customer.Text}}</option>
</select>
</div>

Try ng-change and not onchange
<div ng-app="myApp" ng-controller="myCtrl">
<select class="form-control" ng-change="getPIRData(this.value);">
<option value="0" label="{{DefaultLabel}}"></option>
<option ng-repeat="customer in Customers" value="{{customer.Value}}">{{customer.Text}}</option>
</select>
</div>
A demo code here

As # sinkatonte mentioned in the comment, The way you use angularjs is completely incorrect. You don't need to define angularjs application and controller inside a function. Use the following way to correct your code.
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.getPIRData = function(id) {
$http.get("/PIRDetails/GetPIRStatus/e203")
.then(function (response) {
$scope.myWelcome = response.data;
});
};
});
<div ng-app="myApp" ng-controller="myCtrl">
<select class="form-control" ng-change="getPIRData(this.value);">
<option value="0" label="{{DefaultLabel}}"></option>
<option ng-repeat="customer in Customers" value="{{customer.Value}}">{{customer.Text}}</option>
</select>
</div>
Make sure the response.data in the $http returns data is in correct format and there is a value for this.value used in ng-change="getPIRData(this.value)

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

$http in Angular how to post from form data in to nodejs

I have this form and the data is not appear they do not pass to my back end :
<div ng-controller="searchController">
<form ng-submit="submit()">
<input type="text" name="name" ng-model="namegirl" />
<input type="text" name="namewod" ng-model="namewod" />
<input type="submit"/>
</form>
Now in my controller in script.js is this:
myApp.controller('searchController', ['$scope', '$filter', '$http', function ($scope, $filter, $http) {
let data = {
namegirl :$scope.namegirl,
name :$scope.namewod
};
console.log(data);
$http.post('/wodsearch',data)
.success(function (response) {
console.log(response.data);
})
.error(function (response, status) {
console.log(response);
});
}]);
Now i wand to pass my data from my form to the nodejs in my server i have this code:
app.post('/wodsearch',function(req, res ,next){
// how to get here the data from my angular
});
You call ng-submit="submit()" when you post the form but there is no submit() method in the searchControllers scope. Add it like this
myApp.controller('searchController', ['$scope', '$filter', '$http'
, function ($scope, $filter, $http) {
$scope.submit = function (){
let data = {
namegirl :$scope.namegirl,
name :$scope.namewod
};
console.log(data);
$http.post('/wodsearch',data)
.success(function (response) {
console.log(response.data);
})
.error(function (response, status) {
console.log(response);
});
};
}]);
Assuming you're using Express.
Then the data should be in req.body.

multiple cascading dropdown with Angular & MVC

Firstly apologies that post looks a bit long winded (it is just repeated code, so looks longer than it is). I'm trying to implement a multiple level cascading dropdown - It works fine for the initial and first level (COLUMN1 & COLUMN2) but not for COLUMN3.
Here is the controller:
public JsonResult GetCol1()
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Select(x => new { x.COLUMN1 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult GetCol2(string col1)
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Where(x => x.COLUMN1 == col1).Select(x => new { x.COLUMN2 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
[HttpPost]
public JsonResult GetCol3(string col1, string col2)
{
using (EntityName db = new EntityName())
{
var ret = db.TABLE_NAME.Where(x => x.COLUMN1 == col1).Where(x => x.COLUMN2 == col2).Select(x => new { x.COLUMN3 }).Distinct().ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
Here is the JS:
app.controller('DropdownPopulation', function ($scope, $http) {
//$http service for Getting Column1
$http({
method: 'GET',
url: '/Data/GetCol1'
})
.success(function (data) {
$scope.Col1Data = data;
});
//$http service for getting Column2
$scope.GetCol2 = function () {
$http({
method: 'POST',
url: '/Data/GetCol2',
data: JSON.stringify({ COLUMN1: $scope.col1 })
}).
success(function (data) {
$scope.Col2Data = data;
});
};
//$http service for getting Column3
$scope.GetCol3 = function () {
$http({
method: 'POST',
url: '/Data/GetCol3',
data: JSON.stringify({ COLUMN1: $scope.col1, COLUMN2: $scope.col2 })
}).
success(function (data) {
$scope.Col3Data = data;
});
};
};
Finally here is the html / angular:
<!-- Column 1 -->
<div ng-controller="DropdownPopulation">
<div class="form-group">
<label class="control-label col-sm-2" for="Column1">Column1</label>
<div class="col-sm-10">
<select class="form-control" name="Column1"
data-ng-model="col1" id="Column1"
data-ng-options="c.COLUMN1 as c.COLUMN1 for c in Col1Data "
data-ng-change="GetCol2()">
<option value="" disabled selected>Select Col 1</option>
</select>
</div>
</div>
<!-- Column 2 -->
<div class="form-group">
<label class="control-label col-sm-2" for="Column2">Column2</label>
<div class="col-sm-10">
<select class="form-control" name="Column2"
data-ng-model="col2" id="Column2"
data-ng-options="c.COLUMN2 as c.COLUMN2 for c in Col2Data "
data-ng-change="GetCol3()"
data-ng-disabled="!Col1Data" >
<option value="" disabled selected>Select Col 2</option>
</select>
</div>
</div>
<!-- Column 3 -->
<div class="form-group">
<label class="control-label col-sm-2" for="Column3">Column3</label>
<div class="col-sm-10">
<select class="form-control" name="Column3"
data-ng-model="col3" id="Column3"
data-ng-options="c.COLUMN3 as c.COLUMN3 for c in Col3Data"
data-ng-disabled="!Col2Data" >
<option value="" disabled selected>Select Col 3</option>
</select>
</div>
</div>
</div>
Col3Data is actually returning empty when there is data in the database.
If you know why Col3Data is not returning back anything then your help would be most appreciated.
Many thanks
Shaheen
Okay i found out what the problem was. When doing the following:
data-ng-options="c.COLUMN1 as c.COLUMN1 for c in Col1Data
I was using 'values' for the first part rather than a 'key', so this was not returning data back.
changing to the following worked:
data-ng-options="c.COLUMN1_KEY as c.COLUMN1 for c in Col1Data
Viplock, thanks for your help as I found:
var dataToSend={ COLUMN1: $scope.col1, COLUMN2: $scope.col2 };
very helpful.
Regards,
Shaheen K
If there will be some issue with digest cycle not worked , you can try using $scope.$apply() like
Update For sending data
$scope.GetCol3 = function () {
var dataToSend={ COLUMN1: $scope.col1, COLUMN2: $scope.col2 };
$http({
method: 'POST',
url: '/Data/GetCol3',
data: dataToSend
}).
success(function (data) {
$scope.Col3Data = data;
$scope.$apply();
});
};

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.

Populate textfield on page opening

I have simple form being opened clicking on tab
<form name="instructions" class="form form-horizontal" ng-controller="InstructionsPage">
<div class="form-group">
<label for="instruction">Instructions</label>
<textarea id="instruction" rows="5" class="form-control" ng-model="instructions">
</textarea>
</div>
<button class="btn btn-primary" data-ng-click="saveInstructions()">Save</button>
</form>
and related controller
angular.module('myApp.controllers')
.controller('InstructionsPage', ['$scope', function ($scope) {
use strict';
$scope.saveInstructions = function() {
var data = $scope.instructions;
// post request with data from textfield inside
}
}]);
How to receive data with GET-request to populate textfield with default/previously saved data? Thank you!
You can just update your $scope.instructions variable which is bound to the <textarea> ng-model from your controller like this:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
$scope.instructions = response;
}, function errorCallback(response) {
});

Categories

Resources