HTML
<div ng-controller="Part2ctrl">
<form novalidate name="f1" ng-submit="SaveData()">
<input type="text" name="tname" ng-model="tab1.Name" ng-class="Submitted?'ng-dirty':''" required autofocus />
<br/> CountryName <select ng-model="CountryID" ng-options="I.CountryID as I.CountryName for I in CountryList" ng-change="GetStatesd()"></select> StateName
<select ng-model="StateID" ng-options="I.StateID as I.StateName for I in StateList"></select><input type="submit" value="{{SubmitText}}" />
</form>
</div>
Javascript
angular.module("MyApp").controller("Part2ctrl", function($scope, Revservedata) {
$scope.$watch('f1.$valid', function(dee) {
$scope.isFormValid = dee;
}) $scope.SaveData = function(data) {
if ($scope.SubmitText == "Save") {
$scope.meassage = '';
$scope.isFormValid = true;
if ($scope.isFormValid) {
$scope.SubmitText = "please wait....";
Revservedata.SaveFormData($scope.tab1).then(function(d) {
alert(d);
if (d == "Sucess") {
cleardata();
}
}) Revservedata.GetCountry().then(function(d) {
$scope.CountryList = d.data;
}) $scope.GetStatesd = function(CountryID) {
Revservedata.GetStates($scope.CountryID).then(function(d) {
$scope.StateList = d.data;
})
}
}
});
}).factory("Revservedata", function($http, $q) {
var fac = {};
fac.GetCountry = function() {
return $http.get("/Home/GetCountry");
}
fac.GetStates = function(CountryID) {
return $http.get("/Home/GetStates?CountryID=" + CountryID)
}
fac.SaveFormData = function(data) {
var defer = $q.defer();
$http({
url: "/Home/Create",
method: "POST",
data: JSON.stringify(data),
header: {
'content-type': 'application/json'
}
}) return defer.promise;
}
return fac;
})
Related
I am using angular route for my project. My project structure like below.
index page
<body ng-app="myApp">
<div ng-view></div>
<script src="resources/js/angular.js" type="text/javascript"></script>
<script src="resources/angular/angular-route.js" type="text/javascript"></script>
<script src="resources/js/route.js" type="text/javascript"></script>
<script src="resources/js/quotation.js" type="text/javascript"></script>
<script src="resources/js/container_details.js" type="text/javascript"></script>
<script src="resources/angular/angular-modal-service.js" type="text/javascript"></script>
<script src="/containers/resources/js/user-registration.js" type="text/javascript"></script>
</body>
my route.js file
var app = angular.module('myApp',['ngTable','jcs-autoValidate','ngRoute']);
// configure our routes
app.config(function($routeProvider,$locationProvider) {
$routeProvider
.when('/containers', {
templateUrl : 'template.jsp'
})
.when('/container-details', {
templateUrl : 'container-details.jsp',
controller : 'myCtrl'
})
.when('/quotation-approve', {
templateUrl : 'quotation_approve.jsp',
controller : 'ourCtrl'
})
.when('/user-registration', {
templateUrl : 'user-registration.jsp',
controller : 'userCtrl'
})
$locationProvider.html5Mode(true);
});
/* app.config(["$routeProvider", "$locationProvider", function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);*/
I defined all modules as below:
var app = angular.module("myApp");
when i load page error occur. error said
user registration.js
var app = angular.module("myApp");
app.run(function(defaultErrorMessageResolver, validator) {
validator.setValidElementStyling(false);
defaultErrorMessageResolver.getErrorMessages().then(function(errorMessages) {
errorMessages['min-length'] = 'Username must be at least {0} letters';
errorMessages['max-length'] = 'Username must be {0} letters Only';
errorMessages['pwError'] = "Password should be atleast 8 characters long and should contain one number,one character and one special character";
errorMessages['passwordVerify'] = "password not matched";
errorMessages['validEmail'] = "Please enter a valid email address";
});
});
app.controller('userCtrl', function($scope, $http, NgTableParams, $timeout, $filter) {
$scope.getAllUserDetails = function() {
$http({
method: "GET",
url: "/containers/getUserRolle"
}).then(function mySucces(response) {
$scope.getAllRolesDetails();
$scope.userRolless = response.data.userRolles;
// console.log( $scope.userRolless);
$scope.getDatas();
}, function myError(response) {
$scope.userRolless = response.data.userRolles;
});
}
$scope.getAllTableData = function() {
// $scope.edituserdetails={};
//$scope.edituserdetails.activeuser=true;
$http({
method: "GET",
url: "/containers/getUserRolle"
}).then(function mySucces(response) {
// $scope.getAllRolesDetails();
$scope.userRolless = response.data.userRolles;
// console.log( $scope.userRolless);
$scope.getDatas();
}, function myError(response) {
$scope.userRolless = response.data.userRolles;
});
}
$scope.getDatas = function() {
console.log("tesssst" + $scope.userRolless);
//console.log("tesssst"+$scope.userRolless.object.name);
$scope.tableParams = new NgTableParams({
page: 1, // show first page
count: 5,
// count per page
// filter: {name: '' },
// sorting: { username: "asc" },
}, {
dataset: $scope.userRolless
});
}
$scope.getAllRolesDetailsById = function(roleId) {
$http({
method: "GET",
url: "/containers/getUserRoleById",
params: {
roleId: roleId
}
}).then(function mySucces(response) {
console.log(response.data.userAllRollesById);
$scope.userAllRolles = response.data.userAllRollesById;
$scope.edituserdetails.role = $scope.userAllRolles[0];
// console.log("user Active status"+ $scope.edituserdetails.activeuser);
}, function myError(response) {
console.log(response.data.userAllRolles);
$scope.userAllRolles = response.data.userAllRollesById;
});
}
$scope.editUserFunction = function(usersid) {
$http({
method: "GET",
url: "/containers/getUserDetails",
params: {
userId: usersid
}
}).then(function mySucces(response) {
$scope.edituserdetails = response.data.userDetails;
$scope.username = response.data.userDetails.username;
$scope.getAllRolesDetailsById($scope.edituserdetails.roleId);
console.log(response.data.userDetails);
console.log("user Active status" + response.data.userDetails.userstatus);
if (response.data.userDetails.userstatus === 'Y') {
$scope.edituserdetails.activeuser = true;
} else {
$scope.edituserdetails.activeuser = false;
}
$scope.edituserdetails.password = "";
$scope.edituserdetails.confirmpassword = "";
}, function myError(response) {
$scope.edituserdetails = response.data.userRolles;
});
// console.log(usersid);
}
$scope.getExistingUserValidateFunction = function(userName) {
$http({
method: "GET",
url: "/containers/validateUser",
params: {
userName: userName
}
}).then(function mySucces(response) {
var test = response.data.ExistingUserStatus
console.log("ddddd" + test);
return test;
}, function myError(response) {
// return response.data.ExistingUserStatus;
});
}
$scope.changePassword = function() {
console.log("ddddd" + $scope.edituserdetails.activeuser);
if ($scope.edituserdetails.activeuser) {
activeuserstatus = 'Y';
} else {
activeuserstatus = 'N';
}
console.log("ccccc" + activeuserstatus);
$http({
method: "POST",
url: "/containers/registrationuser",
data: {
"email": $scope.edituserdetails.email,
"username": $scope.username,
"password": $scope.edituserdetails.password,
"id": $scope.edituserdetails.id,
"role": $scope.edituserdetails.role,
"userstatus": activeuserstatus
}
})
.success(function(data) {
$timeout(function() {
$scope.msgType = false;
}, 3000);
$scope.theform.$setPristine();
if (data.errorList.length > 0) {
$scope.fieldErrorList = data.errorList;
$scope.msgType = 'Error';
} else {
$scope.msgType = 'Success';
$scope.getAllTableData();
}
$scope.theform.$setPristine();
// document.body.scrollTop = document.documentElement.scrollTop = 0;
// $scope.resetFunction();
});
// Posting data to php file
}
/* form.$setPristine = function() {
$animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
form.$dirty = false;
form.$pristine = true;
form.$submitted = false;
forEach(controls, function(control) {
control.$setPristine();
});
};*/
$scope.saveUserFunction = function() {
console.log("ddddd" + $scope.edituserdetails.activeuser);
if ($scope.edituserdetails.activeuser) {
activeuserstatus = 'Y';
} else {
activeuserstatus = 'N';
}
console.log("ccccc" + activeuserstatus);
$http({
method: "POST",
url: "/containers/registrationuser",
data: {
"email": $scope.edituserdetails.email,
"username": $scope.username,
"password": $scope.edituserdetails.password,
"id": $scope.edituserdetails.id,
"role": $scope.edituserdetails.role,
"userstatus": activeuserstatus
}
})
.success(function(data) {
console.log($scope.theform);
if (data.errorList.length > 0) {
$scope.fieldErrorList = data.errorList;
$scope.msgType = 'Error';
$scope.theform.$setPristine();
} else {
$scope.msgType = 'Success';
// $scope.edituserdetails = {};
$scope.resetFunction();
$scope.getAllTableData();
$timeout(function() {
$scope.msgType = false;
}, 3000);
$scope.theform.$setPristine();
}
// document.body.scrollTop = document.documentElement.scrollTop = 0;
$scope.resetFunction();
$scope.theform.$setPristine();
});
// Posting data to php file
}
$scope.resetFunction = function() {
$scope.edituserdetails = {};
$scope.username = '';
$scope.edituserdetails.role = $scope.userAllRolles[0];
$scope.theform.$setPristine();
}
$scope.checkPwd = function() {
var str = document.getElementById('pw').value;
if (str.length < 6) {
alert("too_short");
return ("too_short");
} else if (str.length > 50) {
alert("too_long");
return ("too_long");
} else if (str.search(/\d/) == -1) {
alert("no_num");
return ("no_num");
} else if (str.search(/[a-zA-Z]/) == -1) {
alert("no_letter");
return ("no_letter");
} else if (str.search(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[$#$!%*#?&])[A-Za-z\d$#$!%*#?&]{8,}$/) != -1) {
alert("bad_char");
return ("bad_char");
}
alert("oukey!!");
return ("ok");
}
$scope.changePasswordFucntion = function(username) {
console.log(username);
$http({
method: "POST",
url: "/containers/changePassword",
data: {
"password": $scope.edituserdetails.password,
"username": username,
"curruntPassword": $scope.edituserdetails.curruntpassword,
"passwordConfirm": $scope.edituserdetails.confirmpassword
}
})
.success(function(data) {
$timeout(function() {
$scope.msgType = false;
}, 3000);
$scope.theform.$setPristine();
if (data.errorList.length > 0) {
$scope.fieldErrorList = data.errorList;
$scope.msgType = 'Error';
} else {
$scope.msgType = 'Success';
$scope.getAllTableData();
}
$scope.theform.$setPristine();
});
}
$scope.getAllRolesDetails = function() {
$http({
method: "GET",
url: "/containers/getUserAlRolles"
}).then(function mySucces(response) {
// console.log(response.data.userAllRolles);
$scope.userAllRolles = response.data.userAllRolles;
$scope.edituserdetails = response.data.userAllRolles;
$scope.edituserdetails.role = response.data.userAllRolles[0];
}, function myError(response) {
// console.log(response.data.userAllRolles);
$scope.userAllRolles = response.data.userAllRolles;
});
}
})
app.directive("passwordVerify", function() {
return {
require: "ngModel",
scope: {
passwordVerify: '='
},
link: function(scope, element, attrs, myCtrl) {
scope.$watch(function() {
var combined;
if (scope.passwordVerify || myCtrl.$viewValue) {
combined = scope.passwordVerify + '_' + myCtrl.$viewValue;
}
return combined;
}, function(value) {
if (value) {
myCtrl.$parsers.unshift(function(viewValue) {
var origin = scope.passwordVerify;
if (origin !== viewValue) {
myCtrl.$setValidity("passwordVerify", false);
return undefined;
} else {
myCtrl.$setValidity("passwordVerify", true);
return viewValue;
}
});
}
});
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
var app = angular.module("myApp");
This above code does not create module called myApp it just referring an existing module. If you have not yet created the module, then the error will threw which is you have mentioned.
To create the module do this.
angular.module('myApp', []);
Please read this below discussion to more details:
Meaning of the empty array in angularJS module declaration
I am new to Ionic and angularjs. Getting duplicate Http requests for the controllers and services having http request. The following is one of the service I have created using ionic. I am not getting what's causing duplicate request in my code. This is only happening to the tabs with http requests.
login.html
<ion-view view-title="Login" name="login-view">
<ion-content>
<img src="img/epass.png" class="center" style="width: 20em; height: 18em">
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="data.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password">
</label>
<button class="button button-block button-calm" ng-click="login()">Login</button>
</div>
</ion-content>
</ion-view>
app.js
angular.module('starter', ['ionic','ngCordova', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider) {
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('splash', {
url: '/splash',
templateUrl: 'templates/splash.html'
})
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
//Login functionality
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'LoginCtrl'
})
});
contoller
.controller('LoginCtrl', function($scope, User, LoginService, $ionicPopup, $state) {
$scope.data = {};
$scope.login = function() {
LoginService.loginUser($scope)
.success(function(data) {
//TODO What is in the data object?
console.log('response.data.token_id in controllers:'+LoginService.res);
console.log('login success. ' + $scope.data.token );
console.log('$scope.data.username: '+$scope.data.username);
User.cwusername=$scope.data.username;
User.updateToken($scope.data.token);
var token=$scope.data.token;
//User.update(data);
$state.go('tab.dash');
})
.error(function(data) {
const alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
})
service
.factory('User', function(){
var user ={};
var token = 0;
var updateToken = function(id) {
this.token = id;
};
var getToken = function() {
return token;
};
return {
loggedIn: function() {
return user;
},
updateToken: updateToken,
update: function(user) {
this.user = user;
},
getToken: getToken
};
})
.service('LoginService', function($q, $http) {
var url = 'hardcoded url';
var id = 0;
return {
loginUser: function($scope) {
var deferred = $q.defer();
var promise = deferred.promise;
console.log('scope data.username=' + $scope.data.username );
console.log('scope data.password=' + $scope.data.password );
var dataobj = {'username': $scope.data.username, 'login_pwd': $scope.data.password};
var restRespond = "";
console.log('calling for json');
var res = $http.get(url + '/' + $scope.data.username + '/' + $scope.data.password)
.then(function(response) {
console.log('response.data.id in service:'+response.data.id);
id = response.data.id;
restRespond = response.data.response_msg;
console.log(restRespond);
if (id != 0) {
$scope.data.token = id;
console.log('Welcome ' + name + '!');
deferred.resolve('Welcome ' + name + '!');
} else {
console.log('Wrong credentials.' + id);
deferred.reject('Wrong credentials.' + id);
}
});
promise.success = function(fn) {
promise.then(fn);
return promise;
}
promise.error = function(fn) {
promise.then(null, fn);
return promise;
}
return promise;
},
loginToken: function() {
return id;
}
}
})
I am new in angular js. i have making ionic app useing angular js and ionic framework,
This is my service.js file.
In this i have create LoginService for Login control. but its not working.
angular.module('starter.services', ['ngCookies'])
.service('LoginService', function ($q, $http, $cookies, $rootScope) {
return {
loginUser: function (name, pw) {
var deferred = $q.defer();
var promise = deferred.promise;
var user_data = $http.get("http://vanhalterenwatersport.nl/van/webservice/appc/login.php");
user_data.then(function (result) {
var user = result.data;
log(user);
console.log($rootScope.session);
})
function log(user) {
var i;
var isloggedin = false;
for (i = 0; i < user.length; i++) {
if (name == user[i].user_email && pw == user[i].password) {
isloggedin = true;
id = user[i].iduser;
$rootScope.session = id;
break;
}
}
if (isloggedin) {
deferred.resolve('Welcome ' + name + '!');
} else {
deferred.reject('Wrong credentials.');
}
}
promise.success = function (fn) {
promise.then(fn);
return promise;
}
promise.error = function (fn) {
promise.then(null, fn);
return promise;
}
return promise;
}
}
})
This is my controllers.js file
angular.module('starter.controllers', ['ngRoute','ngCookies'])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
})
.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state, $cookies, $rootScope) {
$scope.data = {};
$scope.create = function () {
$state.go('signup');
}
$scope.forgot = function () {
$state.go('forgotpassword');
}
$scope.login = function () {
console.log($scope.data.user_email);
LoginService.loginUser($scope.data.user_email, $scope.data.password).success(function (data) {
var wat = $rootScope.session;
console.log(wat);
$state.go('app.dashboard');
}).error(function (data) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
})
This is my login.html
<ion-view view-title="Login" hide-nav-bar="true" name="login-view">
<ion-content ng-controller="LoginCtrl">
<div class="bar-header padding">
<h1 class="title vanimage"><img src='img/logo.png'></h1>
</div>
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" name="username" ng-model="data.user_email">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" name="password" ng-model="data.password">
</label>
<label class="item">
<button class="button button-block button-positive" ng-click="login()">Log in</button>
</label>
</div>
<div class="padding">
<button class="button button-block button-positive" ng-click="create()">Registeer hier</button>
<button class="button button-block button-positive" ng-click="forgot()">Password Vergeten?</button>
</div>
</ion-content>
</ion-view>
You should put the auth logic in the backend, more secure and efficent.
This is the code I use for login in a service of a Ionic app:
login: function( loginEmail, loginPassword ) {
var deferred = $q.defer();
$http({
method: 'POST',
url: backend_url + '/auth',
// --- change content-type if needed (default = application/json)
// headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: { email: loginEmail, password: loginPassword }
}).then( function( result ) {
if( typeof result.data.token !== 'undefined' ) deferred.resolve( { token: result.data.token } );
else deferred.reject( { error: 'invalid_response' } );
}, function( result ) {
if( typeof result.data.error !== 'undefined' ) deferred.reject( { error: result.data.error, status: result.status } );
else deferred.reject( { error: 'invalid_login' } );
});
return deferred.promise;
},
$http always return a promice, so if you want to do it correctly in your service, using $q try smth like this:
var fn = function (method, url) {
var deferred = $q.defer();
$http(method, url)
.success(function (data) {
deferred.resolve(data);
}
.error(function (data, status) {
deferred.reject({
data: data,
status: status
});
});
return deferred.promise;
}
And if you want to call this function you should do
fn(method, url)
.then(
function(result){
... do if ok (resolve)
},
function( error) {
... do if error (reject)
}
)
You forgot to return the deferred object in your service..
This probably results in the following error:
Cannot read property then of undefined
I've made a basic example to demonstrate the $q service:
Controller - Login function
$scope.login = function login() {
LoginService.loginuser($scope.data.user_email, $scope.data.password)
.then(function onLoginSuccess(response) {
// response should contain 'success' data
$state.go('app.dashboard');
}, function onLoginFailed(error) {
var alertPopup = $ionicPopup.aler({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
Service
var API = {};
function loginUser(email, password) {
var deferred = $q.defer();
$http.get("http://vanhalterenwatersport.nl/van/webservice/appc/login.php")
.then(function onUserLoggedIn(response) {
deferred.resolve(response);
}, function onLoginFailed(error) {
deffered.reject(error);
});
// Make sure to return your promise!
return deferred.promise;
}
API.loginUser = loginUser;
Sidenote: You're also using GET in your login function. For this type of operations, you would typically POST a data-object to your back-end which on his turn will return you a result.
I want to apply facebook like pagination in my application using angularjs.
how can i find on scroll end event on angularjs.
Currently i am trying with below code but it's don't work.
HTML Code
<div ng-app='myApp' ng-controller='StudController'>
<div infinite-scroll='loadMore()' infinite-scroll-distance='2'>
<div ng-repeat="stud in student.lststudent">
{{stud.rollno}}
</div>
</div>
</div>
JS Script Code
<script>
var myApp = angular.module('myApp', ['infinite-scroll']);
myApp.controller('StudController', function ($scope, $http) {
$scope.loadMore = function () {
var data = $.param({
type: "new",
});
$http({
method: 'POST',
data: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'http://www.apiservice.com/api/StudentList/GetStudent'
})
.success(function (data) {
alert(JSON.stringify(data));
$scope.student= data;
});
};
});
</script>
API Json Response Format
{
"lststudent": [{
"rollno": 12,
"name": "sam"
}, {
"rollno": 15,
"name": "peter"
}],
"status": true,
"message": "success"
}
finally i found solution as below.
I have completed it as per solution in below URL.
http://sroze.github.io/ngInfiniteScroll/demo_async.html
Javascript Code
var mainApp = angular.module("mainApp", ['infinite-scroll']);
myApp.controller('studentcontroller', function ($scope, Reddit, $http) {
$scope.reddit = new Reddit();
myApp.factory('Reddit', function ($http) {
var Reddit = function () {
this.items = [];
this.busy = false;
this.pageno = 1;
};
Reddit.prototype.nextPage = function () {
if (this.busy) return;
this.busy = true;
var data = $.param({
rollno: $("#hdnrollno").data('value'),
pageno: this.pageno,
pagesize: 10
});
NProgress.start();
$http({
method: 'POST',
data: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
url: 'http://www.apiservice.com/api/StudentList/GetStudent'
})
.success(function (data) {
scope = data;
var items = data.lststudent;
if (items.length <= 0)
{
NProgress.done();
return;
}
for (var i = 0; i < items.length; i++) {
this.items.push(items[i]);
}
this.pageno = this.pageno + 1;
this.busy = false;
NProgress.done();
}.bind(this));
};
return Reddit;
});
HTML Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngInfiniteScroll/1.2.1/ng-infinite-scroll.min.js"></script>
<div ng-app='myApp' ng-controller='StudController'>
<div infinite-scroll='reddit.nextPage()' infinite-scroll-disabled='reddit.busy' infinite-scroll-distance='1'>
<div ng-repeat="stud in reddit.items">
<span> Rollno </span> {{stud.rollno}}
<span> Student Name</span> {{stud.name}}
</div>
</div>
</div>
I am using angular and the data is coming back from my api call. The problem is my list is not populating.
first partial:
<div ng-controller="CustomerController" data-ng-init="init()" class="col-md-2">
<select ng-model="customerKey" ng-options="customer.Key as customer.Value for customer in customers"></select>
</div>
second partial:
<div ng-controller="CustomerController">
<div class="col-md-2 col-md-offset-5" style="outline: 1px solid black; margin-top: 1%">
<div class="text-center">
<div class="radio-inline" ng-repeat="customerOption in customerOptions">
<input type="radio" id="{{customerOption.Value}}" name="customer" ng-change="getCustomers(customerType)" ng-model="customerType" ng-value="customerOption.Key" ng-checked="customerOption.Checked" />{{customerOption.Value}}
</div>
</div>
</div>
</div>
Controller:
var customer = angular.module('customer', []);
customer.controller('CustomerController', [
"$scope", "customerService",
function($scope, customerService) {
$scope.customerOptions = CustomerOptions;
$scope.getCustomers = function(customerType) {
$scope.showContent = false;
customerService.get(customerType).then(function (data) {
$scope.customers = data;
});
};
$scope.init = function() {
$scope.getCustomers("1");
}
}
]);
service:
app.service('customerService', [
"$http", function ($http) {
this.get = function(customerType) {
var customers;
if (customerType == "1") {
getProduction().then(function(result) { customers = result.data; });
} else if (customerType == "2") {
getTest().then(function(result) { customers = result.data; });
} else {
getAll().then(function(result) { customers = result.data; });
}
return customers;
};
var getTest = function () {
return $http({
method: "GET",
url: "api/Customer/GetTest",
})
.success(function (data) {
return data;
});
};
var getProduction = function () {
return $http({
method: "GET",
url: "api/Customer/GetProduction",
})
.success(function (data) {
return data;
});
};
var getAll = function () {
return $http({
method: "GET",
url: "api/Customer/GetAll",
})
.success(function (data) {
return data;
});
};
}
]);
If you click on any of the radio buttons, they return the appropriate list to the service function; however, I cannot get the select list to populate with that data
The problem is that the service is returning customers object instead of promise, which the controller method is looking for.
It should work if you return the promise from the service and leave the success/error handling to the controller.
app.service('customerService', [
"$http", function ($http) {
this.get = function(customerType) {
var customers;
if (customerType == "1") {
return getProduction();
} else if (customerType == "2") {
return getTest();
} else {
return getAll();
}
};
Controller:
$scope.getCustomers = function(customerType) {
$scope.showContent = false;
customerService.get(customerType).then(function (results) {
$scope.customers = results.data;
});
};
The then handlers in your customerService get() method are assigning the results of the HTTP call to a local customers variable, but this accomplishes nothing. By the time that happens, customers has already been returned to the caller as undefined, and you are most likely getting an error when you call then() on that value.
You need to return a promise from get() and the then() handlers inside get() need to have return statements in them:
this.get = function(customerType) {
if (customerType == "1") {
return getProduction().then(function(result) { return result.data; });
} else if (customerType == "2") {
return getTest().then(function(result) { return result.data; });
} else {
return getAll().then(function(result) { return result.data; });
}
};
There is quite a bit of duplication here, and this can be consolidated:
this.get = function(customerType) {
var customerPromise =
(customerType === "1") ? getProduction()
: (customerType === "2") ? getTest() : getAll();
return customerPromise.then(function (result) { return result.data; });
};