angularjs data is not adding to service - javascript

I am using angularjs and ajax. I want to get the data from the webservice pass to controller. For passing the value to controller i am using holder (It's a factory method or service). It is working without webservice. But when i am calling data from web the data is getting correct but it is not updating to holder. My code is given below. When clicking the button "data1". I want to print the data from webservice in button name data2. It's not showing any error. And successfully data showing data in console but not adding data to holder.
index.html
<!DOCTYPE html>
<html ng-app="sharing">
<head>
<script data-require="angular.js#1.5.6" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="ChildCtrl">
<button ng-click="increment() name="data1">+</button>{{Holder.value}}
</div>
<div ng-controller="ChildCtrl2">
<h2>Second controller</h2>
<button ng-click="increment() name="data2">+</button>{{Holder.value}}
<button ng-click="" name="data3">+</button>{{Holder.name}}
</div>
</body>
</html>
script.js
// Code goes here
var app = angular.module('sharing', []);
var root="http://xxx.xxx.x.xx:60/Api";
app.factory('Holder', function() {
return {
value: 0,
name:""
};
});
app.controller('ChildCtrl', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
var jData1 = {};
jData1.BDMeetingId ="10003/2017";
var k=null;
console.log(JSON.stringify(jData1));
$.ajax({
type: "POST",
async: true,
url: root+"/Boardmeeting/BoardmeetingDetailsSevice",
data: JSON.stringify(jData1),
contentType: "text/plain",
dataType: "json",
crossDomain: true,
success: function (msg) {
k=msg;
$scope.BMNo=k.BMNo;
console.log(msg);
$scope.Holder.name=$scope.BMNo;
},
error: function (jqXHR, textStatus, errorThrown) {
},
});
};
});
app.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});

if you are using angularjs so please avoid to use jQuery code please remove $.ajax and use $http or $resource its angularjs inbuilt provider.
for more details.
https://docs.angularjs.org/api/ng/service/$http
https://docs.angularjs.org/api/ngResource/service/$resource

I have got the answer when using the angularjs webservice instead of ajax webservice.
script.js
var app = angular.module('sharing', []);
var root="http://xxx.xxx.x.xx:60/Api";
app.factory('Holder', function() {
return {
value: 0,
name:""
};
});
app.controller('ChildCtrl', function($scope, Holder, $http) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
var jData1 = {};
jData1.BDMeetingId ="10003/2017";
console.log(JSON.stringify(jData1));
$http({
method: 'POST',
url: root+"/Boardmeeting/BoardmeetingDetailsSevice",
headers: {
'Content-Type': 'text/plain', /*or whatever type is relevant */
'Accept': 'application/json' /* ditto */
},
data: JSON.stringify(jData1)
}).then(function(response) {
console.log(response);
var k=response;
$scope.BMNo=k.BMNo;
console.log(response.data.BMNo);
$scope.Holder.name=response.data.BMNo;
},
function(response) { // optional
// failed
});
};
});
app.controller('ChildCtrl2', function($scope, Holder) {
$scope.Holder = Holder;
$scope.increment = function() {
$scope.Holder.value++;
};
});

Related

Why is my datasource not returning all my data in Angular grid application>?

Let me first preface this by saying...I'm a noob and have been pouring over documentation already but I have not found a resolution.
I have built a custom report in PowerSchool SIS using AngularJS to form my grid and am using JSON data to fill it. The problem I am currently having is the grid is only populating 100 items even though there are close to 200 record items.
This is my JS:
//Begin Module - Loads AngularJS
define(['angular', 'components/shared/index'], function(angular) {
var attApp = angular.module('attApp', ['powerSchoolModule']);
// var yearid = window.location.search.split("=")[1];
//Begin Controller
attApp.controller('attCtrl', ['$scope', 'getData', '$attrs', function($scope, getData, $attrs) {
$scope.curSchoolId = $attrs.ngCurSchoolId;
$scope.curYearId = $attrs.ngCurYearId;
loadingDialog();
$scope.attList = [];
//Sets definition of the var dataSource to pull PowerQueries
var dataSource = {
method: "POST",
url: "/ws/schema/query/com.cortevo.reporting.attendance.absencebymonthschoolgrade",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
data: {yearid},
dataType: "json",
pages:"50",
};
console.log(dataSource);
//Sets definition of the var dataSource to pull from JSON files
console.log('loading dataSource');
//var dataSource= {method: "GET", url: "attendancedata.json"};
getData.getAttData(dataSource).then(function(retData) {
if (!retData.record) {
alert('There was no data returned');
closeLoading();
} else {
console.log(retData);
if (!!retData.record[retData.record.length]) {
// retData.record.pop();
}
var i = retData.record.length;
while (i--) {
retData.record[i].attendance_date = new Date(retData.record[i].attendance_date) // Changes the text of the attendance date to a JS data
}
//Sets scope of attList and attName
$scope.attList = retData.record;
$scope.attName = retData.name;
console.log($scope.attList);
closeLoading();
}
});
}]); //End Controller
//Begins factory and invokes PowerQueries if available, error message will trigger if no data returned
attApp.factory('getData', function($http) {
return {
getAttData: function(dataSource) {
return $http(dataSource).then(function successCallback(response) {
return response.data;
},
function errorCallback(response) {
alert('There was an error returning data');
});
}
}
}); //End Factory
}); //End Module
We have confirmed there is nothing wrong with my datasource. I'm stuck and could use a guiding word. Any advice would be appreciated.
Try to hit the same endpoint using PostMan, maybe the API is not working.
Also I'm not sure if this url is valid:
url: "/ws/schema/query/com.cortevo.reporting.attendance.absencebymonthschoolgrade"

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

AngularJS requests duplicate

I use AngularJS for my application to send multiple requests to the server. Here is an example of my code
HTML
<body ng-controller="AccessCtrl">
Javascript
mainApp.factory('authService', function ($rootScope, $http) {
return {
access: function () {
$http({
method: 'POST',
url: some_url,
data: 'grant_type=client_credentials',
}).success(function (response) {
console.log(response);
$rootScope.access_token = response.access_token;
});
}
}
});
controllersApp.controller('AccessCtrl', ['FactoryModule', function (FactoryModule) {
var testServices = FactoryModule('services');
testServices.authService.access();
}]);
And here is my console:
enter image description here
I have 2 requests from index and from angular initiators. How to fix this? I want 1 request to get access token.

AngularJS "TypeError: Cannot read property 'protocol' of undefined" When get post data from web service

I'm trying to get data from web service. Here my code.
$scope.savePricing = function(){
var pricing = {
"PricingSchemeId": 0,
"Name": $scope.name,
"LastUserName": "Tan",
"LastModifiedDate": "",
"IsActive": true,
"CurrencyId": $scope.selectedCurrency.CurrencyId,
}
$http({
url: config.addPricing,
data: pricing,
method: "POST"
}).success(function(data){
alert("Success");
}).error(function(data){
alert("Failed");
});
})
But when i run this function, this error is shown:
What can i do now?
config.addPricing is undefined. I can easily reproduce that error as follows:
index.html:
<!DOCTYPE html>
<html ng-app="Foo">
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<script src="my-angular.js"></script>
</head>
<body ng-controller="SomeCtrl">
<button ng-click="go()">Go</button>
</body>
</html>
my-angular.js:
var app = angular.module("Foo", []);
app.controller("SomeCtrl", function($scope, $http) {
var config = {}; // Note the lack of "url" field.
$scope.go = function() {
$http({
url: config.url, // undefined
data: {},
method: "POST"
}).success(function(data) {
console.log("Success: data", data);
}).error(function(data) {
console.log("Error: data", data);
});
};
});

Controller error in Angular Script - [$injector:modulerr]

I'm not sure about the controller syntax. I keep getting an [$injector:modulerr] error which leads me to believe that it's the controller playing up but I'm lost otherwise. My main objective at the moment is that I'm trying to "get" and display all the results from a couchdb database.
<div ng-app="guestBook">
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
<script>
var guestBook = angular.module('guestBook', ['ngRoute'])
guestBook.controller('CouchController', ['$scope', '$http', '$get', function ($scope, $http, $get) {
// View everything in database
$scope.view = function () {
var json = {};
var url = "https://sophia.iriscouch.com/guestbook/_all_docs";
$get({
url: url,
method: 'GET',
data: json,
dataType: "jsonp",
}).success(function (json, status, headers, config) {
console.log(json);
})
};
// Creating a new instance on couchDB
$scope.submit = function () {
var entry = {
"Name": $scope.name,
"Comment": $scope.comment
};
console.log(entry);
var timestamp = Math.round(new Date().getTime() / 1000);
var url = 'https://sophia.iriscouch.com/guestbook/' + timestamp;
console.log(url);
$http({
url: url,
method: 'PUT',
data: entry,
dataType: "json",
withCredentials: true,
headers: {
'Authorization': auth_hash("sophia", "Einstein1")
}
}).success(function (data, status, headers, config) {
console.log(data);
}).error(function (data, status, headers, config) {
console.log(headers);
console.log(config);
});
}
function auth_hash(username, password) {
var str = window.btoa(username + ":" + password);
return 'Basic' + str;
}
}]);
</script>
<form ng-controller="CouchController">
<p>
<input type="text" ng-model="comment">
</p>
<p>
<input type="text" ng-model="name">
</p>
<p>
<button ng-click="submit()">Add</button>
</p>
<p>
<button ng-click="view()">show</button>
</p>
</form>
you specify the dependent ngRoute module like
angular.module('guestBook', ['ngRoute'])
but you didn't add angular-route.js script file. adding that file will solve this.
here is the CDN of ngRoute module
after adding it the code should be like,
<div ng-app="guestBook">
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.6/angular-route.js"></script>
....

Categories

Resources