I'm trying to create a live search function with AngularJS. I got a input field:
<input type="text" placeholder="Search" data-ng-model="title" class="search">
it there away to pass the search keyword inside the scope so i can perform a live search (JS) and display the results directly to the DOM
var app = angular.module("DB", []);
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$http.defaults.headers.common["Accept"] = "application/json";
$http.get('http://api.org/search?query=<need to pass search name here>&api_key=').
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
});
Inside the angular controller use a watch expression.
$scope.$watch('title', function (newValue, oldValue) {
if(newValue != oldValue) {
$http.get('http://api.org/search?query=' + newValue + '&api_key=')
.success(function(data, status, headers, config) { /* Your Code */ })
.error(function(data, status, headers, config) { /* Your Code */ });
}
});
You can use watch as #Justin John proposed, or can use ng-change
when using ng-change your controller should look something like this
app.controller("Controller", function($scope, $http) {
$http.defaults.headers.common["Accept"] = "application/json"; //should be moved to run block of your app
$scope.details = [];
$scope.search= function() {
$http.get("http://api.org/search?query="+$scope.title+"&api_key=")
.success(function(data, status, headers, config) { .... })
.error(function(data, status, headers, config) {//handle errors });
}
});
and your html
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
<input type="text" placeholder="Search" data-ng-model="title" class="search" data-ng-change="search()">
app.controller("Controller", function($scope, $http) {
$scope.details = [],
$scope.search= function() {
var url = "http://api.org/search?query="+$scope.title+"&api_key=";
$http.defaults.headers.common["Accept"] = "application/json";
$http.get(url).
success(function(data, status, headers, config) {
}).
error(function(data, status, headers, config) {
//handle errors
});
};
});
Related
I'm at a loss on this. I have checked the forums and can't seem to find a solution.
I'm working on creating an ionic app to pull json feeds into the app and have them process. I have one feed setup, in one angular module, that is pulling some data perfectly fine. But when I try to create this second module, the feed var it errors, but if I hard code the URL in the $http.get it works fine.
This code errors with TypeError: Cannot read property 'protocol' of undefined:
angular.module('mwre.services', [])
.factory('PropertyFeed', function($http) {
var listings = {
residential: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2",
land: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2"
};
var content = "http://somewebsite/api-access/get/mostwantedrealestate/properties/"
return {
getPropertiesContent: function(section, successCallback, errorCallback){
$http.get(listings[section])
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
},
getPropertyItem: function(id, successCallback, errorCallback){
$http.get(smalldesc + id)
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
}
}
});
However, making the following change to the $http.get works:
angular.module('mwre.services', [])
.factory('PropertyFeed', function($http) {
var listings = {
residential: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2",
land: "http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2"
};
var content = "http://somewebsite/api-access/get/mostwantedrealestate/properties/"
return {
getPropertiesContent: function(section, successCallback, errorCallback){
$http.get("http://somewebsite/api-access/get/mostwantedrealestate/categories/1?limit=2")
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
},
getPropertyItem: function(id, successCallback, errorCallback){
$http.get(smalldesc + id)
.success(function(data, status, headers, config) {
successCallback(data);
})
.error(function(data, status, headers, config) {
errorCallback(status);
});
}
}
});
I can't seem to figure out what I've got wrong in my code.
Here is the controller that is running that feed. It works perfectly fine when the URL is hardcoded.
angular.module('mwre.controllers', [])
.controller('PropertiesCtrl', function($scope, $state, $stateParams, $log, $ionicPopup, PropertyFeed) {
$scope.items = [];
$scope.successGetPropertiesContent = function(data) {
$scope.maxIntro = 100;
$scope.items = data.properties;
for (var i = 0; i < $scope.items.length; i++) {
$scope.items[i].smalldesc = $scope.items[i].smalldesc.replace(/<[^>]+>/gm, '');
if ($scope.items[i].smalldesc.length > $scope.maxIntro) {
$scope.items[i].smalldesc = $scope.items[i].smalldesc.substr(0, $scope.maxIntro) + '...';
}
}
};
$scope.errorGetPropertiesContent = function(status) {
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error reading property category content',
template: 'Please check your network connection'
});
alertPopup.then(function(res) {
$log.debug('Error reading property category content');
});
};
$scope.showAlert();
};
PropertyFeed.getPropertiesContent($stateParams.propertiesId, $scope.successGetPropertiesContent, $scope.errorGetPropertiesContent);
$scope.goToContent = function(id) {
$state.go('app.properties', { propertiesId: id });
};
})
.controller('PropertyCtrl', function($scope, $state, $stateParams, $log, $ionicPopup, PropertyFeed) {
$scope.item = null;
$scope.successGetPropertyItem = function(data) {
$scope.item = data;
};
$scope.errorGetPropertyItem = function(status) {
$scope.showAlert = function() {
var alertPopup = $ionicPopup.alert({
title: 'Error reading property listing',
template: 'Please check your network connection'
});
alertPopup.then(function(res) {
$log.debug('Error reading property listing');
});
};
$scope.showAlert();
};
PropertyFeed.getPropertyItem($stateParams.propertyId, $scope.successGetPropertyItem, $scope.errorGetPropertyItem);
});
Hello I have a simple question but I'm running into problems. I edited some code that I found on line. I'm trying to utilize an Angular http service to retrieve JSON data but it doesn't seem to be working
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
My code example is below
http://codepen.io/jimmyt1001/pen/dPVveN
You spelled wrong sucess should be success
CODE
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
you should use a service for this:
json.service('getJson', ['$http', function ($http) {
var promise = null;
//return service
return function () {
if (promise) {
return promise;
} else {
promise = $http.get('url');
return promise;
}
};
}]);
function MainCtrl($scope, getJson) {
getJson().success(function (data) {
$scope.json = data;
});
};
Remember to inject the service name in your controller.
tl;dr
It should be like this:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http)
{
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config)
{
$scope.posts = data;
})
.error(function(data, status, headers, config)
{
// log error
});
});
I.e. you're missing a dot (.) before success and your success is incorrectly typed (you type sucess).
Original
Your code should be structured like this:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
As explained in the docs.
Yours is like this:
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
Wherea you're missing a dot (.) before the success, and your success is spelled wrong (yours is sucess).
It's decent practice to copy existing demos until you're certain on how they're really setup. Also, use your developer tools to catch easy bugs like this.
It's also possible that your dropbox call is simply invalid, but if you fix your code accordingly then the error method should be able to catch it and you should be able to see the error.
I'm new to JavaScript and AngularJS. I'm tryin' to build up a very simple CRUD application. Here is the code of my controller:
(function() {
var app = angular.module('form.user', []);
app.directive('formusergui', [function(){
return {
restrict: 'E',
templateUrl: './js/views/user.form.html',
controller: function($scope, $http) {
this.formToBean = function() {
var ent = {};
ent.id = null;
ent.name = $scope.name;
ent.desc = $scope.desc;
ent.reg = Date.now;
ent.linkImgProfile = null;
ent.type = null;
return ent;
};
this.create = function() {
$http.post('./services/users', JSON.stringify(this.formToBean()))
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
})
.error(function(data, status, headers, config) {
$scope.esito = "error: " + JSON.stringify(data);
});
};
this.delete = function() {
$http.delete('./services/users', JSON.stringify(this.formToBean()))
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
})
.error(function(data, status, headers, config) {
$scope.esito = "error: " + JSON.stringify(data);
});
};
...
},
controllerAs: 'userForm'
};
}]);
})();
formToBean function collects data by the form. As the create function works well (REST service is called), the delete function broke with this error:
TypeError: Cannot assign to read only property 'method' of {"id":null,"name":"john","desc":"doe","linkImgProfile":null,"type":null}
I found similar questions about this kind of error but still I can't get what's going wrong.
for the delete method in the $http, the second parameter is a configuration, in your request instead of configuration related data, simple the json object is passed, refer the api for the $http.delete
https://docs.angularjs.org/api/ng/service/$http#delete
$http.delete('./services/users/:idtodelete')
.success(function(data, status, headers, config) {
$scope.esito = "success: " + JSON.stringify(data);
});
I can't save break line text into my database, how to solve this issue?
My save data suppose to be like this
I want to ask something.
Can I?
Not like this
I want to ask something. Can I?
html
<textarea name="" cols="" rows="" class="form-control" ng-model="rule.message" required></textarea>
<button type="submit" class="btn btn-default" ng-click="create()">Save</button>
js
myControllers.controller('MemberRuleCreateCtrl', ['$scope', '$location',
'$http',
function($scope, $location, $http) {
$scope.rule = {};
$scope.create = function() {
$http({
method: 'GET',
url: 'http://xxxxx.my/api/create_rule.php?&message=' + $scope.rule.message
}).
success(function(data, status, headers, config) {
alert("Rule successful created");
$location.path('/member/rule');
}).
error(function(data, status, headers, config) {
alert("No internet connection.");
});
}
}
]);
Just use the encodeURIComponent() function to encode the newlines correctly into the URL so it will be seen by the server correctly when you submit the GET request.
So your JS becomes:
myControllers.controller('MemberRuleCreateCtrl', ['$scope', '$location',
'$http',
function($scope, $location, $http) {
$scope.rule = {};
$scope.create = function() {
$http({
method: 'GET',
url: 'http://xxxxx.my/api/create_rule.php?&message=' + encodeURIComponent($scope.rule.message)
}).
success(function(data, status, headers, config) {
alert("Rule successful created");
$location.path('/member/rule');
}).
error(function(data, status, headers, config) {
alert("No internet connection.");
});
}
}
]);
I have a list of places that I am printing list of places, and the idea is when the user clicks on the place it takes the user to another page where the details of the place can be viewed. How can I achieve this?
HTML:Page1
<li ng-repeat="place in places.places">
{{place.name}}
</li>
Page2:
<table ng-controller="UncatCtrl">
<tr>
<td>Name: </td><td>{{place.place.name}}</td>
</tr>
<tr>
<td>placeID: </td><td ng-model="PlaceID">{{place.place.placeID}}</td>
</tr>
</table>
Angular:
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/uncatdetails', {
templateUrl: 'templates/uncatpost.html',
controller: 'UnCatPostCtrl'
})
}])
.controller('UnCatPostCtrl', function ($scope, $http) {})
.controller('UncatCtrl', function ($scope, $http) {
$http.get('http://94.125.132.253:8000/getuncategorisedplaces').success(function (data, status, headers) {
$scope.places = data;
console.log(data);
$scope.message = 'Uncategorised places';
})
$scope.showplace = function(placeID) {
$http({method: 'GET', url: 'http://94.125.132.253:8000/getitemdata?ID=' + placeID}).
success(function(data, status, headers, config) {
$scope.place = data; //set view model
console.log(data);
console.log(placeID);
$scope.view = 'templates/detail.html';
})
.error(function(data, status, headers, config) {
$scope.place = data || "Request failed";
$scope.status = status;
$scope.view = 'templates/detail.html';
});
}
})
try it
.when('/uncatdetails/:id', {templateUrl: 'ftemplates/uncatpost.html',
controller: 'UnCatPostCtrl'})
in your HTML
ng-href="uncatdetails/{{place.placeID}}"
in your controller, add this inject $routeParams
$scope.id = $routeParams.id;