how to call http request on ng-click event? - angularjs

I am using angularjs on front end. I have two input boxes on index.html (namely first-name and last-name), and one button. On the click of button (ng-click="search()") I want to call an http GET request with first-name and last-name as parameters. And then I want to show the response in the same page in some other DIV tag. How would I achieve this?

HTML:
<div ng-app="MyApp" ng-controller="MyCtrl">
<!-- call $scope.search() when submit is clicked. -->
<form ng-submit="search()">
<!-- will automatically update $scope.user.first_name and .last_name -->
<input type="text" ng-model="user.first_name">
<input type="text" ng-model="user.last_name">
<input type="submit" value="Search">
</form>
<div>
Results:
<ul>
<!-- assuming our search returns an array of users matching the search -->
<li ng-repeat="user in results">
{{user.first_name}} {{user.last_name}}
</li>
</ul>
</div>
</div>
Javascript:
angular.module('MyApp', [])
.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.user = {};
$scope.results = [];
$scope.search = function () {
/* the $http service allows you to make arbitrary ajax requests.
* in this case you might also consider using angular-resource and setting up a
* User $resource. */
$http.get('/your/url/search', { params: user },
function (response) { $scope.results = response; },
function (failure) { console.log("failed :(", failure); });
}
}]);

Related

Apply jquery after rendering angularJS HTML

i have rendering HTML after AngularJS call
Its controller is
App.controller('controller', ['$scope', '$http', '$sce', '$routeParams', '$location', function ($scope, $http, $sce, $routeParams, $location) {
$http({
//http call
}).then(function (response) {
$scope.requestpurpose = $sce.trustAsHtml(response.data.requestpurpose);
$scope.$watch('requestpurpose', function(newValue, oldValue) {
if(typeof newValue != 'undefined'){
alert(newValue);
showAlreadySelected();
}
});
}]);
and its jquery script is
<script type="text/javascript">
// it will show the div depending on purpose of request
function showAlreadySelected(){
if ($("#1").is(":checked")) {
$("#veterinarian-info").show();
} else {
$("#veterinarian-info").hide();
}
}
</script>
This is my HTML
<div class="row purpose-box" >
<div class="col-sm-12" ng-bind-html="requestpurpose"></div>
</div>
and after ajax call below html is renering in ng-bind-html
<div class="boxes-check">
<div class="box-one">
<input checked="checked" rev="Annual exam" type = "checkbox" name = "request_purpose[]" ng-model=formData.request_purpose[1] onChange="angular.element(this).scope().changePurpose(this)" value = "1" class = "md-check" id = "1" >
</div>
<div class="box-two">
<label title="" for="1">
<span></span>
<span class="check"></span>
<span class="box"></span> Annual exam
</label>
</div>
</div>
<div class="boxes-check">
<div class="box-one">
<input checked="checked" rev="Spay or neuter surgery" type = "checkbox" name = "request_purpose[]" ng-model=formData.request_purpose[2] onChange="angular.element(this).scope().changePurpose(this)" value = "2" class = "md-check" id = "2" >
</div>
<div class="box-two">
<label title="" for="2">
<span></span>
<span class="check"></span>
<span class="box"></span> Spay or neuter surgery
</label>
</div>
</div>
but i am facing problem is after angular load its calling showAlreadySelected function but does not selected "#1" and one thing if any body can help is any Jquery function which will hit whenever input element with id "#1", "#2" render into my ng-bind-html div.
First, I would move the watcher outside the then because you're registering a new watcher everytime you make the ajax call.
I tried, it works to have a number as ID (but not recommended though). We'll need your HTML code as well cause it should work the way you've implemented. Is the #1 node added by the ajax call ( = present in $scope.requestpurpose) or is it always present in the DOM ?
Also, can you add a console.log in the showAlreadySelected function to be sure it's called.
EDIT
App.controller('controller', ['$scope', '$http', '$sce', '$routeParams', '$location', function ($scope, $http, $sce, $routeParams, $location) {
$http({
//http call
}).then(function (response) {
$scope.requestpurpose = $sce.trustAsHtml(response.data.requestpurpose);
showAlreadySelected();
});
}]);
I have bind class with DOMSubtreeModified to detect changes within a div
$('.purpose-box').bind("DOMSubtreeModified",function(){
showAlreadySelected();
});

ng-click inside ng-repeat doesnt work

I have html which looks like one below, I have 2x ng-click in whole code in both situation I call same function. Both functions are in same controller.
<div class="tagselect tagselect--frameless">
<div class="combobox__body combobox__body--open combobox__body--frameless" ng-show="focus">
<ul class="list-unstyled">
<li class="combobox__item" ng-repeat="pos in listCtrl.positions | filter:query as results"
ng-click="listCtrl.choosePosition(pos)">{{pos.name}}
</li>
</ul>
</div>
</div>
<div class="col-md-2 no-padding">
<button type="button" class="btn btn-success" ng-click="listCtrl.chosenPositions(789456)">Add</button>
</div>
controller looks like:
myApp.controller('ListCtrl', ['$scope', '$cookies', '$http', function ($scope, $cookies, $http) {
var listCtrl = {
candidates: [],
positions: [],
chosenPositions: [],
init: function () {
listCtrl.getCandidates();
listCtrl.getPositions();
},
getCandidates: function () {
$http.get('candidates.json').then(function (res) {
listCtrl.candidates = res.data;
});
},
getPositions: function () {
$http.get('positions.json').then(function (res) {
listCtrl.positions = res.data;
});
},
choosePosition: function (position) {
console.log(position);
}
};
listCtrl.init();
$scope.listCtrl = listCtrl;
}]);
I double check for missspells and make sure its not because of function (I create a new one with simple console log).
Problem is that button click correctly call function but ng-repeat <li ng-click=""> doesnt do anything. I read in angular documentation that ng-repeat create new scope but this should be still okey in my opinion as soon as I use reference to object listCtrlchoosePosition()
Can someone tell me what I am doing wrong?
Thanks
EDIT: Plunker example:
http://plnkr.co/edit/ooUQA2n1Vyj8RZtsQ1Pj?p=preview
ng-blur is doing something weird, so I'm going to suggest you to change the $scope.focus value from the ListCtrl instead of using the ng-blur.
html file
<!-- more html code -->
<!-- input without ng-blur directive -->
<input class="tagselect__input" placeholder="Position" ng-focus="focus=true" ng-model="query">
<!-- more html code -->
<li class="combobox__item" ng-repeat="pos in listCtrl.positions | filter:query as results" ng-click="listCtrl.choosePosition(pos)">{{pos.name}}
<!-- more html code -->
js file
// more code goes here.
choosePosition: function (position) {
//alert('Going to choosen position');
//$scope.query = position.name;
$scope.focus = false; // Hide div options from here.
// rest of your code.
},
// more code goes here.
Working in this plunkr

AngularJS: How to call function on onsubmit inside the controller as ng-submit

I am developing mobile app in angularJS, ionic framework and cordova. I am having a scenario where form data i am submitting to server and when server respond me with the status as 200 i am navigating user to the confirmation page. My code is:
<ion-view title="Fill the Form" ng-controller="formSubmit">
<ion-content class="padding-vertical" ng-repeat="htmlValue in HTML">
<form name="fieldForm" id="{{htmlValue.Id}}" method="post" onsubmit="submitFormData($(this).serialize(), $(this).attr('id'))">
<div class="bootstrap" ng-bind-html="htmlValue.Html | unsafe">
</div>
<div class="padding">
<button class="button button-block button-calm">
Submit
</button>
</div>
</form>
<div class="clearfix"></div>
</ion-content>
The function i have written below the index.html page before the body ends.
<script type="text/javascript">
function submitFormData(serializedData,value){
var data = serializedData;
$.ajax({
url: base_url+"put/putFormFilledRawData.php?id="+value,
type: "POST",
data: data,
success: function(tableData){
alert('success');
}});
return false;
};
</script>
Thing is when response arrives as 200 i have to navigate through $state.go() function and for that this function needs to be accessed inside the controller. For that i tried ng-submit at the place of onsubmit but is always shows me error: submitFormData is not a function. How to make it work inside controller from front view forms submit call?
The more angular way of doing it is following:
HTML :
<ion-view title="Fill the Form" ng-controller="formSubmit">
<ion-content class="padding-vertical" ng-repeat="htmlValue in HTML">
<form name="fieldForm" id="{{htmlValue.Id}}" ng-submit="submitFormData(htmlValue)">
<div class="bootstrap" ng-bind-html="htmlValue.Html | unsafe">
</div>
<div class="padding">
<button class="button button-block button-calm">
Submit
</button>
</div>
</form>
<div class="clearfix"></div>
</ion-content>
Controller :
angular.module('formSubmitModule', [])
.controller('formSubmit', ['$scope', function($scope, $http) {
$scope.HTML = []; //Assuming you are getting the array of objects here
$scope.submitFormData= function(formObj) {
$http({
url: '/someUrl',
method: "POST",
params: {paramA: valueA, paramB: valueB}
});
};
(Another flavour of $http service to pass the params in the URL)
This is how you should be making the ajax call and POST the form data in angularJS.
P.S. You can also explore the 'promises' that are returned by the $http service of the angularjs rather then dealing with success and error callbacks.
Look at the documentation of ng-submit
You need to create a controller or a directive and bind the function to the $scope.
Check below example
<script>
angular.module('submitExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}]);
</script>
<form ng-submit="submit()" ng-controller="ExampleController">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>

Select some data and then persist to next controller/view in Angularjs

I am bringing in some simple data via a service that uses angular-resource like so:
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function (InvoiceService) {
var vm = this;
InvoiceService.query(function (data) {
vm.invoices = data;
});
vm.submit = function (form) {
console.log(form)
};
});
And the html:
<form name="invoices" role="form" novalidate>
<ul>
<li ng-repeat="invoice in vm.invoices">
<input type="checkbox" id="{{'id-' + $index}}" />
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="vm.submit(invoices)" />
</ul>
</form>
Everything works fine; the data is displays in the view as expected.
The question:
What I'd like to do is be able to select a checkbox, grab the bit of data associated with that checkbox, and pass it along to the next controller/view on submit. How can I do this?
So, what do I do next? Am I on the right track?
**EDIT: added all angular code to help clarify
Posting answer as reply too big to be useful.
You should be using $scope to isolate the controller's data from the rest of the page.
Read up about ng-model http://docs.angularjs.org/api/ng/directive/ngModel and how to use it to two-way-bind checkbox value to a controller variable. No need to use theFormName if you call $scope.submit = function() { } as your ng-model variable will be available in $scope already.
angular.module('InvoiceService',
['ngResource'])
.factory('InvoiceService', function ($resource) {
return $resource('data.json');
})
.controller("DashboardListCtrl", function ($scope, InvoiceService) {
InvoiceService.query(function (data) {
$scope.invoices = data;
});
$scope.submit = function () {
// FIXME to access a property of each $scope.invoices
console.log('checkbox1=' + $scope.invoices[0].checkbox1);
};
});
Then the HTML:
<form role="form" novalidate ng-controller="DashboardListCtrl"><!-- EDIT: added ng-controller=, remove name= -->
<ul>
<li ng-repeat="invoice in invoices"><!-- EDIT: remove 'vm.' -->
<input type="checkbox" id="{{'id-' + $index}}" ng-model="invoice.checkbox1" /><!-- EDIT: added ng-model= -->
<p><strong>Order:</strong></p>
<p>{{invoice.order}}</p>
</li>
<input type="submit" value="Continue" ng-click="submit()" /><!-- EDIT: remove 'vm.' -->
</ul>
</form>

Why isn't the Angular ng-click event firing?

I've been following a course to learn angularjs and I can't seem to get a simple ng-click binding to work.
HTML:
<body ng-controller="MainController">
<div ng-app="githubViewer">
<h1>{{message}}</h1>
<div>{{ error }}</div>
{{username}}
<form name="searchUser">
<input type="search" placeholder="Username to find" ng-model="username" />
<input type="submit" value="Search" ng-click="search(username)" />
</form>
<div>
<div>{{user.name}}</div>
<img ng-src="http://www.gravatar.com/avatar/{{user.gravatar_id}}" title="{{user.name}}">
{{user.gravatar_id}}
</div>
</div>
</body>
Javascript:
(function () {
var module = angular.module("githubViewer", []);
var MainController = function ($scope, $http) {
var onUserComplete = function (response) {
$scope.user = response.data;
};
var onError = function (reason) {
$scope.error = "Could not fetch the user";
$scope.reason = reason;
};
$scope.username = "angular";
$scope.message = "Github Viewer";
$scope.search = function (username) {
$http.get("https://api.github.com/users/" + username)
.then(onUserComplete, onError);
};
};
module.controller("MainController", MainController);
}());
When you click the search button (search for username "odetocode" or "robconery") it is supposed to display an image but the click event does not seem to be firing. I have searched the documentation and looked over the course again but I can't see what I'm doing wrong.
I'm currently using version 1.2.16 of angularjs.
You have the ng-controller declaration outside of the ng-app declaration right now:
<body ng-controller="MainController">
<div ng-app="githubViewer">
It should be the other way around, or have both on the same element
<body ng-app="githubViewer" ng-controller="MainController">
<div>
AngularJS evaluates your code, and checks for any directives you have declared from the ng-app element down, including the element it is declared on; This currently is missing the ng-controller directive, as it is placed on a parent element of the ng-app element.
You need to put the controller within the context of the module to have it within its scope.
Like so
<body ng-app="githubViewer" ng-controller="MainController">
Demo here

Resources