Angularjs working with $filter filter - angularjs

I'm trying to use $filter to filter dataset retrieved from a JSON file within a controller.
here is the data in the JSON file:
[{
"keyword": "key1",
"path": "path1"
}, {
"keyword": "key2",
"path": "path2"
}, {
"keyword": "key3",
"path": "path3"
}, {
"keyword": "key4",
"path": "path4"
}, {
"keyword": "key5",
"path": "path5"
}]
Then I get the data within my controller like this:
$http.get('/sampleJson.txt').then(function (response) {
vm.resultSet=response.data;
});
and then I use $filter to filter the data:
vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});
Finally I use ng-repeat to show the data in the view:
<tbody>
<tr ng-repeat="result in vm.results">
<td>{{result.keyword}}</td>
<td>{{result.keyword}}</td>
</tr>
</tbody>
However the results variable is empty and nothing shows up. It seems to be pretty basic stuff, however I can not figure out what is wrong?
PS: When I declare other variables in the controller like :
vm.message="Hello, Angular!"
It shows up in the view.

I wrote a solution using $scope. The filter in this solution works. I don't know why you use vm but the $http service works asincronously, and the line
vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});
should be in the body of the then() function.
Here is a plunk
https://plnkr.co/edit/gwx90oN0cf62JuUF5t2k?p=preview

$http is asynchronous, .then (vm.resultSet=response.data;) executed (when promise get resolved) after vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});
Try this,
$http.get('/sampleJson.txt').then(function (response) {
vm.resultSet=response.data;
vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});
});

Related

How do I get a single value from a json file using angular (without using ng-repeat)?

I have a json file with the following data:
{
"favicons": [
{
"36x36”: "36x36.png",
"48x48": "48x48.png",
"57x57": "57x57.png"
}
],
"header": [
{
"imageUrl": "logo.png",
"subTitle": “blah”,
"backgroundColor": "#c30909"
}
]
}
I'd like to retrieve the value of favicons.36x36 without using ng-repeat.
I have this in my app.controller:
app.controller('myCtrl', function($scope, $http) {
$http.get("data.json").then(function (response) {
$scope.faviconData = response.data.favicons;
})
});
Using {{faviconData}} in my HTML, I can output the entire array.
But {{faviconData.36x36}} results in a parse syntax error.
I have also tried faviconData[0].36x36 but this also results in an error.
Do this
{{faviconData[0]['36x36']}}

In AngularJS, $http doesn't change my select option tag data

I have an issue in AngularJS on using $http to fetch data from server.
Here is my HTML
<select ng-model="foo" ng-options="item as item.name for item in items"></select>
Here is my AngularJS Script
angular.module("myApp").controller("myCtrl", function($scope, $http) {
var $scope.items = [];
$scope.items = [
{
"id": 1,
"name": "item1"
},
{
"id": 2,
"name": "item2"
},
];
getData();
function getData() {
$http.get("ng/getData")
.then(function(response) {
if (response.status == 200) {
$scope.items = response.items;
/*
$scope.items = [
{
"id": 5,
"name": "item11"
},
{
"id": 4,
"name": "item22"
}
];
*/
}
});
}
});
What expect from this code is when $http fetches data from server, then select dropdown data will change. But it's not changing anything. I have also printed the response items in the console inside the success callback.
Maybe I don't understand $http usage well enough. Perhaps when I console out data after getData(); $scope.items doesn't change at all. And I think that maybe $http always run at last stage.
Can anybody help to explain this issue? If my assumption is correct, what is the solution that I am looking for?
I think you simply have to add a track by clause:
ng-options="item as item.name for item in items track by item.id"
Check the response object. When you are using 'then' callback to get the resolved data then the actual API result is stored in the 'data' property of the response. So change your code to
$scope.items = response.data;
Or you can use the success callback to attach the data directly.
$http.get("ng/getData")
.success(function(response) {
if (response.status == 200) {
$scope.items = response.items;
}
});

setting the scope value after the http call in Angularjs

I have a controller in which I make an ajax call. In the success callback I assign some value to $scope variable like below.
$http.get(GlobalService.getDomainUrl() +'/hosts/attr').success(function(data){
//Now that we have made the ajax call we need to first get all the config values..
$scope.classifications = _.allKeys(data);
var config;
_.each(data, function(e) {
$scope.config = _.allKeys(e);
console.log($scope.config);
_.each(config, function(attr){
$scope.attributes = attr;
});
});
});
The data from the server is in the below format:
{
"my_config": {
"cpu": [
"2"
],
"mem": [
"4GB"
]
},
"network_config": {
"my_config": [
"ON",
"OFF",
"NONE"
],
"os_config": [
"LINUX",
"MS",
"OSX"
]
}
}
Inside my html code:
<div class="row">
{{config}}
</div>
When I try to use the values in my html file using {{config}} I am seeing an empty array. On the browser console I am able to see the data since I am printing using console.log statement. Please let me know where I am going wrong.
The issue got resolved. The $scope.config was getting set correctly but since the last item in the array returned from the server was empty that was overwriting the value of the scope.config.

AngularJS binding not occurring on page until a user action

I've got my first angular app which displays some data from a list via ng-repeat.
The controller for the view sets a few variables to scope - some directly in the function and another from an API call.
The data from the in function load is showing up in that ng-repeat. The data from the service call doesn't show up (debugging shows the function is being called and data returned and set in scope).
I've got a filter on and if I type anything in it then the data shows up. Or when I click to another view the data flashes onto the page briefly before it loads the new view.
Here is some view code (the items works, venues does not):
<div ng-repeat="item in items">
{{ item.firstName }}
</div>
<div ng-repeat="venue in venues">
{{ venue.details }}
</div>
And here is the controller (data is coming back from the call):
$scope.items = [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
];
var client = new WindowsAzure.MobileServiceClient("url", "key");
var query = client.getTable("venues").read().done(function (results) {
$scope.venues = results;
}, function (err) {
alert("Error: " + err);
});
I'm wondering if maybe the binding is happening before the data is returned from the API?
I added a div and this line into the function and it is printing the results to the page no issues:
document.getElementById("venueslist").innerHTML = JSON.stringify(results);
Thank you for reading.
Looking at your code client.getTable doesn't look like it is using any of angularJs $http or $timeout service. So you will have to wrap the assignment in scope.$apply() so that the $digest cycle is run and the bindings are updated in the view.
var query = client.getTable("venues").read().done(function (results) {
$scope.$apply(function () {
$scope.venues = results;
});
}, function (err) {
alert("Error: " + err);
});
Side note: why are you doing JSON.parse(JSON.stringify(results)), you can directly use results if it is a json object.

Angular Factory Manipulating Data (CRUD) with function in the Factory

I have a simple Angular App that uses a factory to pull a list of items from a "JSON" file. Eventually this will be connected to a database but for now I'm starting with just pulling from a static file. The JSON file contains an array of items. I'm really trying to understand how do I get a reference to my data in the factory after the promise has been returned to the controller.
My Factory is setup as follows:
angular.module("myApp").factory("ServiceTypeFactory", ['$http', function ($http ) {
return {
ServiceTypes: function () {
return $http.get('json/servicetypes.json').success
(
function (data) {
return data;
});
},
find: function (id) {
return _.findWhere(data, {ID:id}); // Not sure how to get access to the data
}
}
}]);
This works great I can share the Factory across multiple controllers. The part I'm missing is how do I reference a specific array item from my json file and update it in my controller. I'm not following how to get a reference to the actual data so when I modify the item in one controller it the change would be reflected in another controller.
In both of my controllers I have the following code to get a reference to the data initially.
var popService = function (data) {
$scope.ServiceTypes = data;
}
// IF at ANY time the Service Types have not been loaded we will populate them.
if (typeof $scope.ServiceTypes === "undefined") {
ServiceTypeFactory.ServiceTypes().success(popService);
}
My understanding is my $scope.ServiceTypes has really a reference to the data. How do I back in my factory in a function get access to the actual single source of my data. I get that the factory returns the data with functions an object but I'm missing how to reference this data back in my factory to manipulate it. In the future I want to perform CRUD operations on it for the time being I'm just trying to work out the mechanics.
What my JSON file looks like:
{
"serviceTypes": [
{
"ID": "1001",
"ServiceTypeName": "111111",
"Description": "aaaaaaa"
},
{
"ID": "1002",
"ServiceTypeName": "222222",
"Description": "bbbbbbb"
},
{
"ID": "1003",
"ServiceTypeName": "3333333",
"Description": "ccccccc"
},
{
"ID": "1004",
"ServiceTypeName": "444444",
"Description": "dddddddd"
},
{
"ID": "1005",
"ServiceTypeName": "5555555",
"Description": "eeeeeee"
}
]
}
Just needed to clean the code up a little. Watching a couple of quick example on egghead.io made it clear.

Resources