Unable to Pass Variable from controller to service in AngularJS - angularjs

I'm trying to pass a zip code to a service that runs an API call using this zip. The problem is, every time I enter a zip and search, the zip code is not passed to the service properly and my HTTP request sends with the zip code as undefined.
Here is my controller:
angular.module('MainCtrl', []).controller('MainController', ['$scope', 'Reps', function($scope, Reps) {
$scope.search = function() {
Reps.search($scope.zipCode)
.success(function(response) {
console.log('Success ' + response);
})
.failure(function(response) {
console.log('Failure ' + response);
})
}
}]);
My service:
angular.module('MainService', []).factory('Reps', ['$http', function($http) {
var root = 'https://www.api.com/locate?';
var apiKey = '&apikey=foo';
var fields = '&fields=bar';
return {
search: function(zipCode) {
var query = root + zipCode + apiKey + fields;
return $http({
method: 'POST',
url: query
})
}
}
}])
My form:
<form method="post" enctype="text/plain" class="form-inline">
<div class="form-group">
<label for="searchForRep">Zip Code:</label>
<input type="text" class="form-control" id="searchForRep" ng-model="zipCode" placeholder="Zip Code (11216)">
</div>
<button ui-sref="reps" ng-click="search()" type="submit" class="btn btn-default">Submit</button>
</form>
So, as mentioned, the zip code does not seem to pass to my service correctly, which is causing the HTTP request to send as:
https://www.api.com/locate?undefined&apikey=foo&fields=bar
Any idea what the issue is with my code?

As per your code it should work. It is working on my plunker, except you did not add your service module to your controller module like:
angular.module('MainCtrl', ['MainService']).controller('MainController',
Plunker here: http://plnkr.co/edit/Ey3K5eF5h56dqWTji5uX?p=preview

Related

Angular 1.5 - Clear form after submit

I have read through all of the suggested postings on this, but I can't seem to clear the form fields after I submit.
I am using controller as syntax, but even if I try to use $scope with $setPristine, I still can't make it work.
This SO answer is what I am following:
https://stackoverflow.com/a/37234363/2062075
When I try to copy this code, nothing happens. No errors, nothing is cleared.
Here is my code:
app.controller('HiringRequestCtrl', function ($http) {
var vm = this; //empty object
vm.ctrl = {};
vm.saveChanges = function() {
//console.log(vm);
$http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(vm)
})
.success(function (response) {
//great, now reset the form
vm.ctrl = {};
})
.error(function (errorResponse) {
});
}
});
and my form looks like this:
<div ng-controller="HiringRequestCtrl as ctrl">
<form id="form" name="ctrl.myForm">
...
<input type="text" name="proposalName" ng-model="ctrl.proposalName"/>
<input type="submit" id="saveButton" value="Submit" class="button" ng-click="ctrl.saveChanges()" />
...
</form>
</div>
I would really prefer not to use $scope.
There's some fundamental issues with the way you've structured this. I think your use of vm.ctrl and then also ng-controller="HiringRequestCtrl as ctrl" is confusing you. Below are my recommended [untested] changes. (I would also suggest moving the $http stuff into a service and using .then() and .catch() because .success() and .error() are deprecated).
Controller
.controller('HiringRequestCtrl', function($http) {
var vm = this; // self-referencing local variable required for when promise resolves
vm.model = {};
vm.saveChanges = function() {
$http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(vm.model)
})
.success(function(response) {
//great, now reset the form
vm.model = {}; // this resets the model
vm.myForm.$setPristine(); // this resets the form itself
})
.error(function(errorResponse) {});
}
});
HTML
<div ng-controller="HiringRequestCtrl as ctrl">
<form id="form" name="ctrl.myForm" ng-submit="ctrl.saveChanges()" novalidate>
<input type="text" name="proposalName" ng-model="ctrl.model.proposalName" />
<input type="submit" id="saveButton" value="Submit" class="button" />
</form>
</div>
Update
Service
.service('hiringService', function($http) {
var service = {};
service.createPost = function(model) {
return $http({
method: 'POST',
url: '/hiringrequest/createPost',
data: angular.toJson(model)
});
}
return service;
}
Controller
.controller('HiringRequestCtrl', function(hiringService) {
vm.saveChanges = function() {
hiringService.createPost(model)
.then(function(response) {
// if you need to work with the returned data access using response.data
vm.model = {}; // this resets the model
vm.myForm.$setPristine(); // this resets the form itself
})
.catch(function(error) {
// handle errors
});
}

How to link Laravel controller function with Angular View

I am working on a laravel web application , recently i embedded angularjs for searching data from database. But for now i just used an array to search.In my AngularJs Module i point to search function as $scope.url = 'Students#search'; but this is not working for me. I want to know that how to tell AngularJS $scope.url to point to this search function in my Controller so that user can search data easily.
I have search function in Students Controller:
public function search(){
$data = file_get_contents("php://input");
$objData = json_decode($data);
// Static array for this demo
$values = array('php', 'web', 'angularjs', 'js');
// Check if the keywords are in our array
if(in_array($objData->data, $values)) {
echo 'I have found what you\'re looking for!';
}
else {
echo 'Sorry, no match!';
}
}
MyApp.js File :
function SearchCtrl($scope, $http) {
$scope.url = 'Students#search'; // The url of our search
// The function that will be executed on button click (ng-click="search()")
$scope.search = function() {
// Create the http post request
// the data holds the keywords
// The request is a JSON request.
$http.post($scope.url, { "data" : $scope.keywords}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
$scope.result = data; // Show result from server in our <pre></pre> element
})
.
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
}
Angular Search View:
<div ng-controller="SearchCtrl">
<form class="well form-search">
<label>Search:</label>
<input type="text" ng-model="keywords" class="input-medium search-query" placeholder="Keywords...">
<button type="submit" class="btn" ng-click="search()">Search</button>
<p class="help-block">Try for example: "php" or "angularjs" or "asdfg"</p>
</form>
<pre ng-model="result">
#{{result}}
</pre>
</div>
You may create a route first. For example-
Route::get("/search", ["as" => "studentSearch", "uses" => "Students#search"]);
then you can set it like
$scope.url = '{{ route ("studentSearch") }}';
Or if its not a blade template then you have to manually set the url. Like
$scope.url = '/search';

Angularjs: Cannot display array items using ng-repeat

I am using AngularJs to retrieve the data from ASP.Net Controller.
The Json data is retrieved from the server, but can't figure out why cannot display array items when using the ng-repeat:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$http({ method: 'GET', url: '/home/listvalues?listid=3' }).then(function (response) {
$scope.lookupItems = response;
console.log($scope.lookupItems);
},
function (error) { alert("error"); });
// console.log($scope.listItems);
});
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
The Json Retrieved from the server:
[{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}]
The most likely issue (assuming that your app and controller are constructed and referenced properly) is that the object returned from the promise contains a .data property which actually holds your JSON data.
Try this:
$http({ method: 'GET', url: '/home/listvalues?listid=3' })
.then(function (response) {
$scope.lookupItems = response.data;
console.log($scope.lookupItems);
},
function (error) {
alert("error");
});
I think you just forgot to wrap your app with ng-app:
var app = angular.module('Appp', []);
app.controller('metadataCtrl', function ($scope, $http) {
$scope.lookupItems = {};
$scope.lookupItems = [{"ListValueID":13,"Translation":{"TranslationID":0,"Value":"Important","LanguageValues":{"ar":"مهم","en":"Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":14,"Translation":{"TranslationID":0,"Value":"Less Importance","LanguageValues":{"ar":"أقل أهمية","en":"Less Importance"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0},
{"ListValueID":15,"Translation":{"TranslationID":0,"Value":"Very Important","LanguageValues":{"ar":"كثير الأهمية","en":"Very Important"}},"ListCategory":{"ListID":4,"Translation":{"TranslationID":0,"Value":"","LanguageValues":{"ar":"","en":""}}},"Parent":0}];
console.log($scope.lookupItems);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="Appp">
<form name="myForm" ng-controller="metadataCtrl" class="my-form">
<div ng-repeat="item in lookupItems">
{{$index}}
{{item.ListValueID}}
</div>
</form>
</body>
You probably misspelled Appp. Make sure your module definition in your javascript:
var app = angular.module('App', []); //Changed to App from Appp
matches your app declaration in your html
<div ng-app="App">
...controller declaration...
...body.....
</div>

Login in angularjs

I have an idea of how to use post method for login, however, our new requirement is my API team has provided get method. How is this used in angular? Please help me. I am stuck on this problem as I am new to angular. Below is the API for get method:
http://183.82.48/HospitalManagementSystem/Service1.svc/LoginVerification/{EMAILID}/{PASSWORD}
You can try to construct the URI yourself.
<form ng-app="login" ng-controller="loginCtrl">
<span>Email</span><input ng-model="emailId" type="text" required><br>
<span>Password</span><input ng-model="password" type="password" required><br>
<button ng-click="login()">Login</button>
</form>
<script>
var app = angular.module('login', []);
app.controller('loginCtrl', function($scope, $http) {
$scope.login = function() {
$http.get('http://183.82.0.48/HospitalManagementSystem/Service1.svc/LoginVerification/' + $scope.emailId + '/' + $scope.password).then(
function (response) {
console.log(response.data);
// ...
},
function (error) {
console.log(error);
// ...
}
)
}
});
</script>

Form data always going null for text field in angular js and rest service spring

I am new to AngularJS and not sure where I am missing, though I know its a minor mistake which I am committing. Please help me out with below scenario.
I have a form where in I write a post {textArea} and click submit button, which calls ng-click=createPost() method.
It goes to controller.js which is:
app.controller('MyCtrl1', ['$scope', 'PostFactory', '$location', function ($scope, PostFactory, $location) {
/* callback for ng-click 'createUser': */
$scope.createPost = function() {
alert("in createPost" + $scope.post.postText);
alert("in createPost" + $scope.post);
PostFactory.create($scope.post)
$scope.posts.push($scope.post.postText);
$scope.post = "";
$location.path('/view1');
}
$scope.posts = PostFactory.query();
/*UserFactory.get({}, function (userFactory) {
$scope.firstname = userFactory.firstName;
})*/
}]);
and my service.js is:
var services = angular.module('ngdemo.services', ['ngResource']);
//alert("In services");
services.factory('PostFactory', function ($resource) {
// alert("Reached services.js");
return $resource('/ngdemo/web/posts', {}, {
query: {
method: 'GET',
//params: {},
isArray: true
},
create: {method: 'POST'}
})
});
my Spring controller which is exposed as service and have post method:
#RequestMapping(/*value = "/add",*/ method = RequestMethod.POST)
public #ResponseBody String addPost(#ModelAttribute(value = "") Post post, BindingResult result) {
System.out.println("Post value : " + post.getPostText());
//post.setPostId();
post.setPostTags("#dummy");
postService.addPost(post);
return "redirect:/";
}
my form :
<form novalidate="novalidate" class="form-horizontal">
<!-- Textarea -->
<div class="form-group">
<div class="col-md-4">
<textarea ng-model="post.postText" rows="4" cols="300" name="inputQuestion" id="post.postText" class="form-control expand" placeholder="What you want to pingle today?"></textarea>
</div>
<br>
<!-- Button -->
<div class="col-md-4">
<button ng-click='createPost()' class="btn btn-default plus"> Pingle it! </button>
</div>
</div>
</form>
Problem is : always Post value in controller is coming as null, have tried with $scope.post and $scope.postText but no joy!
Please let me know where I am missing?????
UPDATE:
How can we pass a form object to Spring Controller in controller.js?? Post is my Domain object
it worked, once I replaced #ModelAttribute with #RequestBody, somehow it was preventing the data to be populated in my object. After setting #RequestBody, it worked!Thanks all!

Resources