I've seen so many ways to do this, but most are pretty old and I want to make sure I'm doing this correctly. Right now, the way I'm using isn't working and I feel like I'm missing something.
I'm getting the JSON back fine, I just need to get it to display in a table after I click the button.
Here is the JSON. This is how I'm going to get it from our server, I can't add any "var JSON =" or add any scope like "$scope.carrier" to the data, unless there's a way to add it after I've fetched the data.
{
"carrier":
[
{
"entity": "carrier",
"id": 1,
"parentEntity": "ORMS",
"value": "Medica"
}, {
"entity": "carrier",
"id": 2,
"parentEntity": "ORMS",
"value": "UHG"
}, {
"entity": "carrier",
"id": 3,
"parentEntity": "ORMS",
"value": "Optum"
}, {
"entity": "carrier",
"id": 4,
"parentEntity": "ORMS",
"value": "Insight"
}, {
"entity": "carrier",
"id": 5,
"parentEntity": "ORMS",
"value": "Insight"
}
]
}
Here is the app.js file to bring back the JSON data:
var app = angular.module('myTestApp', []);
app.controller('myController', ['$scope', '$http', function($scope, $http) {
var url = 'test.json';
$scope.clickButton = function() {
$http.get(url).success(function(data) {
console.log(data);
});
}
}]);
And then of course the HTML:
<div class="col-lg-12 text-center">
<button type=button class="btn btn-primary load" ng-click="clickButton()">Click!</button>
<table class="">
<tbody ng-repeat="carrier in carriers">
<tr>
<td>
<h3 class="">{{ module.entity }}</h3>
<h3 class="">{{ module.id }}</h3>
<h3 class="">{{ module.parentEntity }}</h3>
<h3 class="">{{ module.value }}</h3>
</td>
</tr>
</tbody>
</table>
</div>
I'm also wondering if I can use the ng-grid to put this in a table. I know they just upgraded it to ui grid so I'm not sure if this is still a feasible approach.
Also, I'm not getting errors, the data just won't display in the table right now. All I know is its returning the data properly, just not displaying in the table.
Any help is appreciated.
I looked at your plunker seems like you need to:
add angular script
wire the app and the controller
your variable in the repeater is wrong, I change it
take a look to this fixed plunker:
http://plnkr.co/edit/TAjnUCMOBxQTC6lNJL8j?p=preview
$scope.clickButton = function() {
$http.get(url).success(function(returnValue) {
alert(JSON.stringify(returnValue.carrier));
$scope.carriers = returnValue.carrier;
});
}
You never assign the value of the returned array to $scope.carriers.
At the line where you say console.log(data); add this:
$scope.carriers = data.data;
Here is the updated clickButton function (with a variable name change to reduce confusion):
$scope.clickButton = function() {
$http.get(url).success(function(returnValue) {
$scope.carriers = returnValue.data;
});
};
Related
So here's my problem, i'm using AngularJS and i'm getting JSON from PHP, and displaying all my data with ng-repeat. I already have done this.
Now I want to check if some data is in "Array1" and if it is, change the correspndent data from the ng-repeat. I know it sounds really weird, but let me put an example with code:
Here's array1 values
{
"23",
"48",
"51"
}
So when i get the data, it's something like this:
{
id : "23",
name: "example"
}
And for every JSON object i'm using ng-repeat to display them all like this:
<div ng-model="data.posts" ng-repeat="post in posts | orderBy:'-' | unique: 'id'">
...
<button>This button will show if "id" matches</button>
<button>This button will show if "id" not matches</button>
</div>
I want to compare if an id of array1 matches an id from the JSON data and if it matches show one button and if not show other.
I'm on this like 2 weeks, and i can't get the problem solved, and i don't see any way to get it.
Thx for reading at least and sorry for my bad english!
Your array1 should be an array and can add a function in controller to check match id.
in controller:
$scope.array1 = ["23","48","51"];
$scope.checkInArray1 = function(id) {
var index = $scope.array1.indexOf(id);
if(index < 0){
return false;
} else {
return true;
}
};
and in your html:
<button ng-if="checkInArray1(post.id)">This button will show if "id" matches</button><br>
<button ng-if="!checkInArray1(post.id)">This button will show if "id" not matches</button>
Making the assumption that {"23","48","51"} should be a array ["23","48","51"]
You could do something like this:
Working Fiddle: http://jsfiddle.net/ravenous52/rgyom4yd/
myApp.controller('MyCtrl', ['$scope',
function($scope) {
$scope.knownIds = ["23", "48", "51"];
$scope.data = {
posts: [{
id: "23",
name: "example23"
}, {
id: "51",
name: "example51"
}, {
id: "99",
name: "example99"
}]
}
}
]);
<section ng-controller="MyCtrl">
<div ng-repeat="post in data.posts">
<button ng-show="knownIds.indexOf(post.id) >-1">This button will show if "id" matches</button>
<button ng-hide="knownIds.indexOf(post.id) >-1">This button will show if "id" not matches</button>
</div>
</section>
https://jsfiddle.net/alair016/4wc44on1/
<div ng-app='myApp' ng-controller="MyCtrl">
<div ng-model="data.posts" ng-repeat="post in data.posts">
<button ng-if="array1.indexOf(post.id) >-1">{{post.name}} id matches</button>
<button ng-if="array1.indexOf(post.id) == -1">{{post.name}} id does not match</button>
</div>
</div>
var myApp = angular.module('myApp',[])
.controller('MyCtrl', ['$scope', function($scope) {
$scope.array1 = ["23","48","51"];
$scope.data = {
posts : [
{
id : "23",
name: "example"
},
{
id: "24",
name:"second example"
}
]
};
}]);
I got some problems with window.location.href.
In my website I use AngularJS (framework).
I got a table with the following code:
<table id="MAND">
<tbody id="hoveren">
<tr ng-repeat="artist in artists | filter:name">
<td class="user-name"><img id="{{artist.div}}" style="vertical-align: middle;" src="{{artist.img}}"></td>
<td class="user-email" style="vertical-align: middle;">{{artist.name}}</td>
<td class="user-phone" style="vertical-align: middle;">{{artist.description}}</td>
<td class="user-phone" style="vertical-align: middle;">{{artist.country}}</td>
</tr>
</tbody>
</table>
So you see the gives the image a divname.
Then in jQuery, I call the following function:
$("#crunch").click(function() {
window.location.href = "http://example.com/new_url";
});
In this case, the {{"artist.div"}} was equal to crunch, so that's why #crunch.
Why isn't this working?
I click on it but nothing happens.
Is it some sort of stupid mistake anywhere?
Thanks!
Btw, if you want to know, my angularjs part:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
angular.module('App', [])
.controller('Controller', function($scope){
$scope.artists = [
{
"name": "Crunchyroll",
"country": "All countries except Japan",
"img":"images/crunchy.png",
"description":"You can set it to everything you want!",
"div":"crunch"
},
{
"name": "Rhapsody",
"country": "US only, be at the right spot",
"img":"images/rhap.png",
"description":"You can set it to everything you want!"
},
{
"name": "Febreze",
"country": "US only",
"img":"images/feb.jpg",
"description":"You can set it to everything you want!"
},
{
"name": "Kellogs Froot Loops",
"country": "US only",
"img":"images/kel.jpg",
"description":"You can set it to everything you want!"
},
{
"name": "Pure Asia Garcinia Weight Loss",
"country": "US, AU, CA, UK and NZ only",
"img":"images/bottle.png",
"description":"You can set it to everything you want!"
},
{
"name": "Free Computer",
"img":"images/pc.png",
"description":"You can set it to everything you want!"
},
{
"name": "whateveee",
"country": "All countries except Japan",
"img":"images/crunchy.png",
"description":"You can set it to everything you want!",
"div":"crunch"
}
];
});
Don't run btw, didn't know how to put it in.
Thanks!
You need to update your code to following. At the time you are binding the event, there is no element with id #crunch in the html, hence, the binding never takes place.
So, for elements added dynamically, you need to bind events like following.
$(document).on('click', '#crunch', function(){
window.location.href = "http://example.com/new_url";
});
Your code should work provided element with id crunch exists by the time event handler is attached and it seems it doesn't. Use delegated events to solve this problem
$("#MAND").on('click', '#crunch', function() {
window.location.href = "http://example.com/new_url";
});
jQuery should really be a last resort here. Prefer Angular methods when they are available.
Inject $window into your controller:
.controller('Controller', function($scope, $window){
Add this function to your controller:
$scope.go = function(artist) {
$window.location.href = "http://example.com";
};
Change your views to use ng-click:
<img id="{{artist.div}}" ng-click="go(artist)" ...
Plunker demo.
I know this is a bit basic but i'm struggling to get my head round it, I have a web service that returns the follow JSON:
[{"search_id":"1","user_id":"1","all_words":"php","not_words":"C++","one_words":"java","created_at":null,"updated_at":null,"search_name":null},{"search_id":"2","user_id":"1","all_words":"second","not_words":"not","one_words":"one","created_at":null,"updated_at":null,"search_name":null}]
So when it gets to angular I end up with the following:
Array[2]
0: Object
$$hashKey: "object:5"
all_words: "php"
created_at: null
not_words: "C++"
one_words: "java"
search_id: "1"
search_name: null
updated_at: null
user_id: "1"
__proto__:
1: Object
$$hashKey: "object:6"
all_words: "second"
created_at: null
not_words: "not"
one_words: "one"
search_id: "2"
search_name: null
updated_at: null
user_id: "1"
__proto__:
Which is a real pain to work with in ng-repeat, how would I go about being able to access it like so(rough example)
ng-repeat="item in items"
{{ item.search_id }}
to be clear the only way I can get data from it is by doing:
<tr ng-repeat="items in data">
<td ng-repeat="(key, value) in items"> </td>
</tr>
Controller code is here:
testAPI.getSearches().then(function (data) {
$scope.data= testAPI.searchList();
console.log($scope.data);
}, function (error) {
alert("Error in getSearches");
});
getsearches as follows, searchList returns the searches variable:
getSearches: function() {
var deferred = $q.defer();
$http({
url: 'http://localhost/api/api/tray/search/list'
}).success(function (data) {
searches = data;
console.log(data);
deferred.resolve(data);
}).error(function (data) {
alert('Error');
deferred.reject(data);
});
return deferred.promise;
},
Hrm thanks for the responses guys but the plain "item in data" does not work in my case I have to use (key,value) in items inside a nested ng repeat, any ideas what i'm missing?
By the way not sure if this matters put the HTML is inside a partial and i'm using ui router for the navigation?
UPDATE
Thank you all very much for your help, looks like this problem was caused by a typo on a containing HTML element and the controller not being setup properly because I messed up the ui router setup. Once i've had a chance to make sure i've missed nothing else i'll post back.
This seems to be working fine. Just make sure you're data is tied to your $scope.
http://jsfiddle.net/f4zdfh72/
function MyCtrl($scope) {
$scope.data = [{
"search_id": "1",
"user_id": "1",
"all_words": "php",
"not_words": "C++",
"one_words": "java",
"created_at": null,
"updated_at": null,
"search_name": null
}, {
"search_id": "2",
"user_id": "1",
"all_words": "second",
"not_words": "not",
"one_words": "one",
"created_at": null,
"updated_at": null,
"search_name": null
}]
}
<div ng-controller="MyCtrl">
<div ng-repeat='item in data'>
THIS IS DATA: {{item.one_words}}
</div>
</div>
Note: run it in the JSFiddle. Stack snippet is just for code preview
works fine for me: http://plnkr.co/edit/ubiWcF3CemeKo6dzkvNC?p=preview
var app = angular.module("myApp", []);
app.controller('myCtrl', ['$scope', function($scope){
$scope.data = JSON.parse('[{"search_id":"1","user_id":"1","all_words":"php","not_words":"C++","one_words":"java","created_at":null,"updated_at":null,"search_name":null},{"search_id":"2","user_id":"1","all_words":"second","not_words":"not","one_words":"one","created_at":null,"updated_at":null,"search_name":null}]')
}]);
Maybe I am missunderstanding, but this should actually work. Plunker The Example includes the Controller As and $scope approaches.
Controller
angular
.module("app", [])
.controller("MainController", ['$scope', function($scope) {
var vm = this;
var json = '[{"search_id":"1","user_id":"1","all_words":"php","not_words":"C++","one_words":"java","created_at":null,"updated_at":null,"search_name":null},{"search_id":"2","user_id":"1","all_words":"second","not_words":"not","one_words":"one","created_at":null,"updated_at":null,"search_name":null}]';
vm.items = JSON.parse(json);
$scope.items = JSON.parse(json);
}]);
html
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body ng-controller="MainController as vm">
<h1>Items Controller As</h1>
<div ng-repeat="item in vm.items">
{{ item.search_id }}
</div>
<h1>Items $scope</h1>
<div ng-repeat="item in items">
{{ item.search_id }}
</div>
<script data-require="angular.js#1.3.6" data-semver="1.3.6" src="https://code.angularjs.org/1.3.6/angular.js"></script>
<script src="script.js"></script>
</body>
</html>
Edit:
Added my comment from above.
Why do you use two nested ng-repeats? I guess one object of the array should be one row in the table. Therefore
<tr ng-repeat="item in data">
...
<td>{{item.search_name}}</td>
...
</tr>
should work. Unless you need the keys of the object, than you need (key, value).
How to clear multiple select option after saving into DB, i am using ng-model to clear it. Its clearing in back-end but not in UI side.
In controller I am writing:
smsType = {};
smsType.smsTypeId = [];
HTML code:
<div class="form-group">
<select ng-model="smsType.smsTypeId" ui-jq="chosen" multiple
class="w-md"
ng-options="s.id as s.name for s in smsoption.name">
</select>
</div>
Its not reflecting in ui side
Please give me some suggestion i am new to angularjs
Please see demo below
you missed $scope here
smsType.smsTypeId = [];
should be
$scope.smsType.smsTypeId = [];
// Code goes here
angular.module("myApp", []);
angular.module("myApp").controller("SelectCtrl", ["$scope",
function($scope) {
$scope.smsoption = {
name: [{
"id": "122",
"name": "denmark"
}, {
"id": "123",
"name": "france"
}, {
"id": "124",
"name": "italy"
}]
};
$scope.saveit = function() {
console.log($scope.selectCenter);
$scope.smsType.smsTypeId = [];
}
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<h1>ngOption demo</h1>
<div ng-app="myApp">
<div ng-controller="SelectCtrl">
<select ng-model="smsType.smsTypeId" ui-jq="chosen" multiple class="w-md" ng-options="s.id as s.name for s in smsoption.name">
</select>
<hr/>You have chosen:
<span ng-repeat="type in smsType.smsTypeId">{{type}} | </span>
<button ng-click="saveit()">Save</button>
</div>
</div>
The model is the output, not the input. To clear it you need to clear smsoption. The model should reflect the options you have selected, not the other way around.
smsoption = [];
Should do it
I'm having trouble accessing the nested JSON using the ng-repeat directives. I know it is working because the not nested part of the JSON object is displaying.
Here is a plunker of my code: http://plnkr.co/edit/V2iURMa8t7vG9AqDFMOf?p=preview
JavaScript:
var app = angular.module("app", [ ]);
app.controller("AppTest", function($scope){
$scope.currentInfo=[{"id":0,"article":"JavaScript Conquers the World","publisher":"Daily Times","meta_data":{"comments":4}},
{"id":1,"article":"The Problem with Foobar","publisher":"New York Times","meta_data":{"comments":27}}];
$scope.tableInfo=[{"name":"id","dataType":"Integer","isEditable":false},
{"name":"article","dataType":"String","isEditable":true},
{"name":"publisher","dataType":"String","isEditable":false},
{"name":"meta_data.comments","dataType":"Integer","isEditable":false}];
});
HTML:
<body ng-app="app" ng-controller="AppTest as app"
<table>
<tbody ng-repeat="anotherItem in currentInfo">
<tr>
<td ng-repeat="item in tableInfo">{{anotherItem[item.name]}}</td>
</tr>
</tbody>
</table>
</body>
Another solution that is better is to add function in the controller that will resolve the value for you. The issue with your solution is that you need Angular to resolve meta_data.comments, but it is treating it as the string that is used in the array lookup since it has already resolved item.name.
$scope.resolveLookup = function(object, lookup) {
var depth = lookup.split('.').length;
var currentObj = object;
for(var x=0; x<depth; x++) {
currentObj = currentObj[lookup.split('.')[x]];
}
return currentObj;
};
Then change the HTML to look like:
<td ng-repeat="item in tableInfo">{{resolveLookup(anotherItem,item.name)}}</td>
Here is the Plunker: http://plnkr.co/edit/RVd2ncwstyQtCtdhcC9U?p=preview
The issue is that it is putting 'metadata.comments' in the [] and it doesn't realize that it needs to be resolved again by angular. I can't think of fix without changing the data structure of your 'tableInfo' object.
Here is how I would do it.
Change table info to:
$scope.tableInfo = [{
"name": ["id"],
"dataType": "Integer",
"isEditable": false
}, {
"name": ["article"],
"dataType": "String",
"isEditable": true
}, {
"name": ["publisher"],
"dataType": "String",
"isEditable": false
}, {
"name": ["meta_data", "comments"],
"dataType": "Integer",
"isEditable": false
}];
Change your HTML to:
<td ng-repeat="item in tableInfo" ng-if="item.name.length==1">{{anotherItem[item.name[0]]}}</td>
<td ng-repeat="item in tableInfo" ng-if="item.name.length==2">{{anotherItem[item.name[0]][item.name[1]]}}</td>
Here is the Plunker: http://plnkr.co/edit/q9lHZ2TD7WZ74b2f6Ais?p=preview