$http.get not executing functions on success - angularjs

I am doing my first Angular project (ionic framework) where i have to get some data from database and on success I havet to
store it in a variable
navigate to a page where this variable is used.
The page is navigating, but data are not sent.
Here is my search.html code:
<body ng-app="starter" ng-controller="ListCtrl">
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Real Estate</h1>
</ion-header-bar>
<ion-content>
<h4 align="center"> Enter Place or Pincode </h4>
<div class="list list-inset" >
<label class="item item-input">
<input type="text" name="place" ng-model="data.place" value="" placeholder="Place" ng-focus="$scope.placefocus=true;data.pincode=null" ng-blur="$scope.placefocus=false" ng-disabled = "$scope.pincodefocus">
</label>
<label class="item item-input">
<input type="number" name="pincode" ng-model="data.pincode" value="" placeholder="Pin Code" ng-focus="$scope.pincodefocus=true;data.place=null" ng-blur="$scope.pincodefocus=false" ng-disabled="$scope.placefocus">
</label>
</div>
<button class="button button-block button-positive" ng-click="getdata()">
Search
</button>
</ion-content>
</ion-pane>
</body>
And here is my controller code :
app.controller('ListCtrl',function($scope,$http,$location,$window){
$scope.data = {};
$scope.getdata = function(){
//alert($scope.data.place);
$http.get("http://localhost/angular/data.php")
//,{'place':$scope.data.place,'pincode':$scope.data.pincode})
.success(function(response,status,headers,config){
alert(response);
$scope.datas=response;
$scope.navig('/show.html');
})
}
$scope.navig = function(url){
$window.location.href=url;
};
});
and here is my show.html page :
<ion-content>
<div class="list card" ng-repeat="site in datas">
<div class="item item-body">
<a href="#" class="subdued"><img class="full-image" src="img/{{site.image}}" height="150px">
<p>
RS.{{site.price}} &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <span> {{site.square_feet}} sq.ft &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</span><span>{{site.bed}} BHK</span>
</p>
</a>
</div>
</div>
</ion-content>
alert(response) in the controller code alerts [object Object],[object Object],[object Object]
But the output page (show.html) is blank
If I call navig("/show.html") directly from the button click (in search.html) instead of getdata() and change the controller code to the below one, I am getting the result: (But I cannot execute this way because I have to get data from database for particular place and pincode entered)
app.controller('ListCtrl',function($scope,$http,$location,$window){
$scope.data = {};
$http.get("http://localhost/angular/data.php")
//,{'place':$scope.data.place,'pincode':$scope.data.pincode})
.success(function(response,status,headers,config){
alert(response);
$scope.datas=response;
})
$scope.navig = function(url){
$window.location.href=url;
};
});

Don't use the success function, use the .then() function.The code below is from the angular documentation.
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Here is the text from the Documentation
Deprecation Notice
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.

$scope works with in controller only! Instead of $scope use $rootScope.

It might be the promise.
Why don't you try this.
app.controller('ListCtrl',function($scope,$http,$location,$window){
$scope.data = {};
$http.get("http://localhost/angular/data.php")
//,{'place':$scope.data.place,'pincode':$scope.data.pincode})
.then(function(response){
alert(response);
$scope.datas=response;
})
$scope.navig = function(url){
$window.location.href=url;
};
});

Related

How to clear input field onclick?

I have done a lot to fix this, but it's not working. I am using Ionic's searchbar.
My input field gets the class ng-empty when nothing is filled in (so this is the default state). The input field gets a ng-not-empty class when it's filled in.
So, I could fix this with jQuery or something, but I saw that Angular has ways to do this. This is the HTML:
<ion-view view-title="Testing">
<ion-header-bar align-title="center" class="bar">
</ion-header-bar>
<ion-content class="scrollBar">
<ion-searchbar class="searchBar" ng-app="myApp">
<label>
<input class="searchField" type="search" ng-model="itemsSearch"/>
<a class="clear" data-ng-click="saveParentComment()">X</a>
<i class="icon ion-search placeholder-icon"></i>
</label>
</ion-searchbar>
</ion-content>
</ion-view>
I've added this to my controller:
myApp.controller('SearchController', function ($http, $scope, $state) {
$scope.saveParentComment = function () {
$scope.itemsSearch = "";
};
Yet, this is not working and I don't get why. Am I doing something wrong? If so, how can I fix it? I have seen a lot of questions regarding this one, but no answer worked for me. I don't see any errors in the console either...
The only thing I see, is that the anchor gets a new class "activated" when I click on it.
In the angular,every directive create new scope.
itemsSearch is bind to the directive scope and its not visible to controller.
Use it as part of object defined on $scope in controller.
myApp.controller('SearchController', function ($http, $scope, $state) {
$scope.objItem = {itemsSearch : ""};
$scope.saveParentComment = function () {
$scope.objItem.itemsSearch = "";
};
HTML :
<input class="searchField" type="search" ng-model="objItem.itemsSearch"/>
Try this out :-
<input type="text" class="form-control" data-ng-model="searchAll"></input>
<a class="clear" href="" data-ng-click="clearSearch()">X</a>
app.controller("SearchController", function ($scope) {
$scope.searchAll = "";
$scope.clearSearch = function () {
$scope.searchAll = "";
};
});
I don't see anywhere in your view you have put SearchController Also ng-model should work with a dot operator
Try,
<ion-view view-title="Testing" ng-app="myApp" ng-controller="SearchController">
<ion-header-bar align-title="center" class="bar">
</ion-header-bar>
<ion-content class="scrollBar">
<ion-searchbar class="searchBar">
<label>
<input class="searchField" type="search" ng-model="myObj.itemsSearch"/>
<a class="clear" data-ng-click="saveParentComment()">X</a>
<i class="icon ion-search placeholder-icon"></i>
</label>
</ion-searchbar>
</ion-content>
</ion-view>
In controller:
myApp.controller('SearchController', function ($http, $scope, $state) {
$scope.myObj = {};
$scope.saveParentComment = function () {
$scope.myObj.itemsSearch = "";
};
Can you please make sure that you put SearchController,
Can you please try with this
<ion-view view-title="Testing" ng-app="myApp" ng-controller="SearchController">
<ion-header-bar align-title="center" class="bar">
</ion-header-bar>
<ion-content class="scrollBar">
<ion-searchbar class="searchBar">
<label>
<input class="searchField" type="search" ng-model="itemsSearch"/>
<a class="clear" data-ng-click="saveParentComment()">X</a>
<i class="icon ion-search placeholder-icon"></i>
</label>
</ion-searchbar>
</ion-content>
And Function:
$scope.saveParentComment = function () {
console.log("clear");
$scope.itemsSearch = null;
};
If you see clear in console log than you are sure that your function is working fine. And you can set initial value also in controller like for itemSearch like.
$scope.itemsSearch = "Search Here";
I think there is a problem with your controller. First try in console for function is working or not
$scope.saveParentComment = function () {
console.log("working");
};

Nested ng-repeat with different data

I am using AngularJS v1.5.0 in my web application. I have feedbacks of the users which are displayed using ng-repeat. Now whenever the executive clicks on the feedback, I make a server call and fetch the history of user and show it on the panel.
Once the call is successful, I assign the data to the feebackDetails variable which is now the controller scope variable. But I dont want it to have the controller scope, as each feedback will have different user and different data.
<div class="tab-pane fade in" ng-controller="controller-feedback" id="feedback">
<div class="col-md-12">
<div class="row">
<div ng-repeat="feedback in feedbacks track by $index" ng-click="getUserHistory(feedback.userId)" data-toggle="collapse" data-target="#feedback{{$index}}" aria-expanded="false" aria-controls="#feedback{{$index}}">
<div class="alert alert-info">
<div>{{feedback.feedback}}</div>
<div class="collapse" id="feedback{{$index}}">
<div class="well">
<div ng-repeat="feedbackDetail in feedbackDetails track by $index">
<span style="font-weight: bold">Question:</span> {{feedbackDetail.question}} <br>
<span style="font-weight: bold">Answer:</span> {{feedbackDetail.answer}} <br>
<span style="font-weight: bold">Helpful:</span> {{feedbackDetail.helpful}} <br>
<span style="font-weight: bold">Feedback:</span> {{feedbackDetail.feedback}} <br>
<span style="font-weight: bold">Executive:</span> {{feedbackDetail.executive}} <br>
<hr ng-hide="$last">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
This is my controller part.
app.controller('controller-feedback', function ($scope, $http, $rootScope) {
$scope.feedbacks = [];
$scope.feedbackDetails = [];
// This will get the feedbacks
$http
.get(phpUrl + 'test-feedback', {params:{doctorId:doctorId}})
.then(function success(response) {
$scope.feedbacks = response.data.data;
$rootScope.feedbackCount = response.data.data.length.toString();
}, function error(success) {
});
$scope.getUserHistory = function(userId) {
console.log(userId);
$http
.get(phpUrl + 'test-feedback-details', {params:{userId:userId}})
.then(function success(response) {
/**
* This variable $scope.feedbackDetails must be different for each ng-repeat
*/
$scope.feedbackDetails = response.data;
}, function error(success) {
});
};
});
change getUserHistory to accept feedback object.
$scope.getUserHistory = function(feedback) {
var userId = feedback. userId ....
and rather than
$scope.feedbackDetails = response.data;
assign
$scope.feedback.feedbackDetails = response.data;
Inner ng-repeat should use feedback.feedbackDetails.
You could create a directive called feedbackDetail that you put inside your ng-repeat which uses an isolate-scope and you pass in your feedbackDetail from the ng-repeat.
Then when you make the HTTP request from the directives controller and assign it to $scope it would be a scope for just that part of the repeat.

$Scope doesn't work on subpage

this is my controller,
.state('tabs.urunler',{
url:'/urunler',
views:{
'urunler-tab':{
templateUrl:'pages/urunler.html',
controller:'MyCtrl'
}
}
})
.state('tabs.detail',{
url:'/urunler/:aId',
views:{
'urunler-tab' : {
templateUrl:'pages/urunlerDetail.html',
controller : 'MyCtrl'
}
}
})
this is POST method.
$http({
url : apiAddress + 'getUrunler',
method : 'POST',
data : {type}
}).then(function successCallback(response){
$scope.urunler = response.data;
console.log($scope.urunler);
},function errorCallback(response){
console.log("error");
});
this is my urunDetails.html
<ion-item ng-repeat="urun in urunler">
{{urun.title}}
<div class="list">
{{urun.brand}}
<a class="item item-thumbnail-left">
<img src ="{{urun.picture}}">
<h2>{{urun.brand}}</h2>
<p>{{urun.title}}</p>
</a>
</div>
this is the Urun.html
<ion-item ng-repeat="urun in urunler">
<div class="list">
<a class="item item-thumbnail-left" ng-click="changeUrun('Alix Avien')" href="#/tab/urunler/{{urun.title}}">
<img src ="{{urun.picture}}">
<h2>{{urun.brand}}</h2>
<p>{{urun.title}}</p>
</a>
</div>
</ion-item>
The problem is , I can reach {{urun}} in Urun.html, but when I go to subpage of urun.html which is urundetails.html, $scope doesn't work :/. I've looked the response data after reached the urunDetails.html by writing console.log(); Data is coming but I can not see data on the urunDetails.html page. Thanks for help !!
This issue is because you are binding data to the scope variable outside angular scope digest cycle. For this scenario you will have to manually trigger the digest cycle.
There are no. of ways to trigger the digest cycle manually.
I will suggest just use $timeout(function(){}, 0); after $scope.urunler = response.data. This will basically trigger the digest cycle once more by taking care of any clashes if there is any digest cycle already running.
Your two states use the same controller, but each controller instance seems to have its own $scope.
I experimented with this here in this plunkr: https://plnkr.co/edit/qGO3pIDHezym71l7jygU?p=preview
angular.module('myApp', []);
angular.module('myApp').controller('ctrl1', ctrl1);
ctrl1.$inject = ['$scope'];
function ctrl1($scope){
$scope.test = 'Something';
$scope.change = function(){
$scope.test = 'Something else';
}
}
and
<body ng-app="myApp">
<div ng-controller="ctrl1">
<p>
{{test}}
</p>
<button ng-click="change()">Click me!</button>
</div>
<div ng-controller="ctrl1">
<p>
{{test}}
</p>
</div>
</body>
The 'change' function only changes the scope variable in the instance where it is called. My best guess is something similar is happening in your case.
You probably want to use some kind of service to provide your controller with the correct data.
Maybe that helps you with your problem, this is just my best guess though. I unfortunately can't really see what you are trying to do with your provided code samples.

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>

AngularJs how to reload a template page after selecting a charater

I am using http.get and i need to reload a template after selecting a character so that my template gives the answer according to what I selected
The code of the template
<div class="container-fluid" ng-controller="CriterioCtrl">
<div id="result"></div>
<div>
Selected Items:
<div ng-repeat="id in selection">
{{id}}
</div>
</div>
<div ng-repeat-start="crit in data" class="row">
<h2 align="center">{{crit.name}}</h2>
<div ng-repeat="caracter in crit.characters" class="col-md-4">
<div type="checkbox" value="{{caracter.id}}" ng-checked="selection.indexOf(caracter.id) > -1" ng-click="clickSelection(caracter.id)">
<a href="#crit" class="thumbnail" ng-click="clickCriterios(caracter.id)">
<h4 align="center">{{caracter.name}}</h4>
<img ng-src="http://skaphandrus.com/{{caracter.image_url}}"/>
</a>
</div>
</div>
</div>
<div ng-repeat-end>
</div>
<!--<button class="btn" ng-click="toggle()">Toggle</button>
<p ng-show="visible">Hello World!</p> codigo de um botao -->
</div>
This code is for the selection
$scope.selection=[];
$scope.clickSelection = function clickSelection(caracterId) {
var idx = $scope.selection.indexOf(caracterId);
// is currently selected
if (idx > -1) {
$scope.selection.splice(idx, 1);
}
// is newly selected
else {
$scope.selection.push(caracterId);
}
var selectedId = $scope.selection;
console.log(selectedId);
// Check browser support
if (typeof(Storage) != "undefined") {
// Store
localStorage.setItem("idSelect", selectedId);
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("idSelect");
}
};
This code is the http part in another controller
MyApp.controller('EspeciesCtrl', function ($scope, $http) {
$http({
url: 'someurl',
method: "post",
params: {module_id: localStorage.getItem("idMod"),"characters[]": [localStorage.getItem("idSelect")]}
})
.then(function(res){
$scope.data = res.data;
});
});
This is the code of the template that have to change after the selection
<div class="container-fluid" ng-controller="EspeciesCtrl">
<div class="row">
<div ng-repeat="esp in data" class="col-md-6">
<a href="#infEsp" class="thumbnail" ng-click="clickEspecie(esp.id)">
<h4 align="center">{{esp.name}}</h4>
<img ng-src="{{esp.image_src}}"/>
</a>
</div>
</div>
</div>
How can i do that?
edit 1
If I've correctly understood, you may need to use ng-show (https://docs.angularjs.org/api/ng/directive/ngShow) whose boolean value checks if the user selected anything and show the extra bit of code you need, instead of trying to have another http request.
Also, it seems like you are using $scope.data for both the esp and the crit, so you will end up with the errors.
You probably don't need to reload the template.
You may want to use the data in $scope.data inside the template in order to let Angular manage the update on the view. As soon as the $scope.data changes, the rendered HTML changes too.
I can't comment but it would be helpful if you could share the template you are using and be more specific in your request :)

Resources