No Action in angular js - javascript

Below is my code
<script>
var app = angular.module("myApp2", [])
app.controller("ShowController", ['$scope', function ($http) {
$scope.Get = function () {
var adata = { EmpId: 'EmpId' };
var JSon = JSON.stringify(adata);
EmpId = $("#EmpIdb").val();
$http({
method: "Get",
url: servUrl + "Show",
data: JSon,
}).then(function mySucces(response) {
alert(response.data);
}, function myError(error) {
alert(response.statusText);
});
}
}])
</script>
</title>
</head>
<body ng-app="myApp2" ng-controller="ShowController">
<center>
<h3> Please Enter Your Emp Id</h3></br>
<input type ="text" id="EmpIdb" /></br>
<input type="button" id ="Fetch" value="Fetch Details" ng-click="Get();"/>
<div ng-view></div>
</center>
which is not working.
There is no error in the console and I am not able to debug it either.
Any help welcomed

There are multiple problems. But I do not really get why error is not coming
1 . Where is the servUrl coming from?
2 .
$http({
method: "Get",
url: servUrl + "Show",
data: JSon,
})
to
$http({
method: "GET",
url: servUrl + "Show",
data: JSon,
})
3 . Change this in 3rd line
app.controller("ShowController", ['$scope', function ($http) {
to
app.controller("ShowController", ['$scope', '$http', function ( $scope, $http) {
Fix these. then try again.
EDITED
DEMO Plunker with working code.

Change your code like below. You are not passing scope in controller function.
<script>
var app = angular.module("myApp2", [])
app.controller("ShowController", ['$scope', '$http', function ($scope, $http) {
$scope.Get = function () {
var adata = { EmpId: 'EmpId' };
var JSon = JSON.stringify(adata);
EmpId = $("#EmpIdb").val();
$http({
method: "GET",
url: servUrl + "Show",
data: JSon,
}).then(function mySucces(response) {
alert(response.data);
}, function myError(error) {
alert(response.statusText);
});
}
}])
</script>

Try this. just inject $scope and $http in your controller
var app = angular.module("myApp2", [])
app.controller("ShowController", ['$http', '$scope', function ($http, $scope) {
$scope.Get = function () {
var adata = { EmpId: 'EmpId' };
var JSon = JSON.stringify(adata);
EmpId = $("#EmpIdb").val();
$http({
method: "Get",
url: servUrl + "Show",
data: JSon,
}).then(function mySucces(response) {
alert(response.data);
}, function myError(error) {
alert(response.statusText);
});
}
}])

Related

how to pass dropdown list value to a function as a parameter

I have one dropdown list, on the ng-change event I need to pass the dropdown list value to the $scope.getPIRData function so that I can get dynamic results.
<div class="col-sm-4 col-lg-offset-4" ng-controller="myCtrl">
<select class="form-control" ng-model="sel_val" ng-change="getPIRData(sel_val)" ng-options="data.deveui for data in Customers"></select>
</div>
<script>
var app = angular.module('plunker', []);
app.controller('myCtrl', function ($scope, $http, $window) {
$scope.sel_val = 0;
$scope.DefaultLabel = "Loading.....";
var post = $http({
method: "get",
url: "../data.json",
dataType: 'json',
data: {},
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
$scope.Customers = data;
});
post.error(function (data, status) {
});
$scope.getPIRData = function (id) {
$http.get("/PIRDetails/GetPIRStatus/" + id)
.then(function (response) {
$scope.myWelcome = response.data;
console.log(JSON.stringify($scope.myWelcome));
});
};
});
</script>
Screenshot
Pass the value in the ng-change directive.
ng-change="getPIRData(sel_val)"

how to have multiple $http call inside of a ng-repeat

i tried to retrieve two data, one from the API and from my json, when i make the call i receive just the second call on my view.
json 1
[
{
"id": 1,
"img":"images/clientlogos/21747.jpg"
},
{
"id": 2,
"img": "images/clientlogos/FMI.png"
}
]
jason # from APi call
[
{
"id": 1,
"name": "Enough",
"forecasted": 22,
"budget": 40,
"hoursspent": 3.53999997675419,
"currentcosts": 965.393393660635,
"xerototal": 2800
},
{
"id": 2,
"name": "Fad Ltd",
"forecasted": 96.5,
"budget": 300,
"hoursspent": 199.91000029631,
"currentcosts": 66234.589716303,
"xerototal": 176472
},
]
my factory
app.factory('myFactory', function($http){
return{
client: function(callback){
$http({
method: "GET",
url: "http://www.outleading.co.za/api/api/clientdashboarddata",
cache:true
}).then(callback);
},
list: function(callback){
$http({
method: "GET",
url: "data/Client.json",
cache:true
}).then(callback);
}
};
});
my controller
app.controller('myController', function ($scope, $http, myFactory) {
myFactory.client(function (response) {
var data = response.data;
$scope.myClients = data;
})
myFactory.list(function(response){
var data= response.data;
$scope.myClients= data;
})
};
}
})
my html
inside my ng-repeat i want to get{{client.img}} from my json and {{client.clientname}} from the api call
<div class="card client-card" ng-repeat="client in myClients>
<div class="client-logo">
<img ng-src="{{client.img}}" alt="{{client.name}}">
</div>
</div>
so Any help will be much appreaciated.
You are calling two APIs and overriding the input.
app.controller('myController', function ($scope, $http, myFactory) {
myFactory.client(function (response) {
var data = response.data;
$scope.myClients = data; //Same variable
})
myFactory.list(function(response){
var data= response.data;
$scope.myClients= data; //Same variable
})
};
}
})
Instead of saving data in $scope.myClients in both the calls, use some different variable name. I guess second one should be $scope.lists
Modify factory to return promise it gives you flexibility
app.factory('myFactory', function ($http) {
return {
client: function () {
return $http({
method: "GET",
url: "http://www.outleading.co.za/api/api/clientdashboarddata",
cache: true
});
},
list: function () {
return $http({
method: "GET",
url: "data/Client.json",
cache: true
});
}
};
});
Use $q.all() and wait for all promises to complete
app.controller('myController', function ($scope, $http, myFactory, $q) {
$q.qll(myFactory.client(), myFactory.list()).then(function (result) {
$scope.myClients = result[0].data;
var images = result[1].data;
$scope.myClients.forEach(function(client){
// find index of image for client
var idx= images.findIndex(function(x){
return x.id == client.id
});
client.name = images[idx].name;
})
});
});

Angular JS Service Creation Error

I have created this service.
and using **enrollments.getProperty();**this statement to call this service but it's not working I'm new to angular-JS please let me know where I making the mistake.
var helloAjaxApp = angular.module("myApp", []);
helloAjaxApp.service('enrollments', [ '$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment=function () {
$http({
url : 'enrollments',
method : "GET"
}).then(function(response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function(value) {
enrollments = value;
}
};
}]);
use angular.module()
(function () {
'use strict';
angular.module("helloAjaxApp")
.service('enrollments', ['$scope', '$http', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
var enrollments = null;
enrollment();
$scope.enrollment = function () {
$http({
url: 'enrollments',
method: "GET"
}).then(function (response) {
enrollments = response.data;
alert("enrollments");
});
};
return {
getProperty: function () {
return enrollments;
},
setProperty: function (value) {
enrollments = value;
}
};
}]);
});
Angular has 2 ways of defining a service: service and factory.
here you can see the difference: https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html
The basic difference is that service is like a constructor, so you don't return an object from it but define the properties using this keyword:
this.getProperty = function () {
return enrollments;
}
When using the factory method, is expects an object to be returned with the exposed properties/functions.
You are using the factory syntax, so just change the definition to use factory:
helloAjaxApp.factory('enrollments', [ '$scope', '$http', function ($scope, $http)
You should go for a proper service structure like so:
var helloAjaxApp = angular.module("myApp", []);
function EnrollmentService($scope, $http) {
let _this = this;
this.enrollments = null;
this.getEnrollments = function() {
return $http({
url: 'enrollments',
method: 'GET'
}).then(function(response) {
_this.enrollments = response.data;
return _this.enrollments;
})
};
this.setEnrollments = function(enrollments) {
_this.enrollments = enrollments;
}
}
helloAjaxApp.service('enrollments', ['$scope', '$http', EnrollmentService]);
Then, use the service anywhere else:
enrollmentService
.getEnrollments()
.then(function(enrollments) {
// You can use the data here.
console.log(enrollments);
});
The controller code
LoginService is service name you have to pass as a parameter to controller
var loginModule = angular.module('LoginModule',[]);
loginModule.controller('logincontroller', ['$rootScope','$scope','$http','$window','$cookieStore',
'LoginService',logincontrollerFun ]);
function logincontrollerFun($rootScope, $scope, $http, $window,$cookieStore, LoginService,RememberService) {
$scope.loginTest = function() {
LoginService.UserStatus($scope, function(resp) {
console.log("response of login controller ::: ", resp);
///write ur code
});
}
}
service code
var loginModule = angular.module('LoginModule')
loginModule.factory("LoginService",[ '$http', LoginServiceFun ])
function LoginServiceFun($http) {
function UserStatus($scope,callback){
var targetRequestPath='./url';
var targetRequestParamsREQ={'email':$scope.email,'password':$scope.passWord};
return $http({
method: 'POST',
url: targetRequestPath,
headers: {'Content-Type': 'application/json'},
data: targetRequestParamsREQ
}).then(function (response){
console.log('Response Data : ', response.data);
callback( response.data );
})
}
return {
UserStatus:UserStatus
}
}

using $http service, can not find the data

Here are my code -
var app = angular.module('chartApp', []);
app.controller('artistCtrl', ['$scope', '$http', function($scope, $http) {
$scope.artists =
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json'}
}).success(function(result) {
return result.data;
});
console.log($scope.artists);
}]);
How to view the original data from json file?
Move the assignment statement inside the success block:
.success(function(result) {
$scope.artists = result.data;
})
Also, one more thing to note is the console.log($scope.artists) statement right after the $http block will still print undefined because it is executed before the promise is resolved.
Try this it will work :
var app = angular.module('chartApp', []);
app.controller('artistCtrl', ['$scope', '$http', function($scope, $http) {
$scope.artists =
$http({
method: 'GET',
url: 'http://ws.audioscrobbler.com/2.0/?method=chart.gettopartists',
params: {api_key: 'e8452c5962aafbb3e87c66e4aaaf5cbf', format: 'json'}
}).success(function(result) {
$scope.artists = result.data;
}).error(function(msg) {
$scope.err = msg;
});
}]);

sharing $scope between 2 function within one controller

app.controller('AppCtrl', ['$scope', '$http','$stateParams','getTopicContent', function($scope,$http,$stateParams,getTopicContent){
$scope.ionLoader = true;
getTopicContent.request($stateParams.topicId).then(function(response){
$scope.threadContent = response.data;
}).finally(function(){
$scope.ionLoader = false;
});
$scope.loadPages = function ($scope) {
if(totalPages > 1){
$http({
url: "http://someurl.php",
method: "GET",
params: {topicId: $stateParams.topicId,page : 2}
}).success(function(data){
$scope.threadContent.push(data);
});
}
}
}]);
I got an error saying push of undefined. loadPages only fire when the user scrolled to the bottom of the page so I don't think it's an async issue, probably $scope problem? getTopicContent is my service.
You can use promise for async working and remove parameter $scope in loadPages like that:
app.controller('AppCtrl', ['$scope', '$http','$stateParams','getTopicContent', function($scope,$http,$stateParams,getTopicContent){
$scope.ionLoader = true;
var promise = getTopicContent.request($stateParams.topicId).then(function(response){
$scope.threadContent = response.data;
}).finally(function(){
$scope.ionLoader = false;
});
$scope.loadPages = function() {
if(totalPages > 1){
$http({
url: "http://someurl.php",
method: "GET",
params: {topicId: $stateParams.topicId,page : 2}
}).success(function(data){
promise.then(function(none) {
$scope.threadContent.push(data);
});
});
}
}
}]);

Categories