I have a list of name's and id's. I have displayed it with ng-repeat property. I want to show the corresponding id's along with the name in 1 second on its click.
$scope.showFn = function() {
$scope.showPopup = true;
$timeout(function(){
console.log("timeout");
$scope.showPopup = false;
}, 1000);
};
I have created a plunker https://plnkr.co/edit/kvkgwp60Bxq2MrHrr5Rr?p=preview
Now showing all the id's in a single click. Please help. Thanks.
Try with below in HTML:
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js#*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="main">
<ul>
<li ng-repeat="item in items">
{{item.name}}
<span ng-show="showPopup && item.id == shownId">{{item.id}}</span>
</li>
</ul>
</body>
</html>
Controller will be like below:
var app = angular.module('app', [])
.controller('main', function($scope, $timeout) {
$scope.items = [{
"name": "one",
"id": "1"
}, {
"name": "two",
"id": "2"
}, {
"name": "three",
"id": "3"
}, {
"name": "four",
"id": "4"
}, {
"name": "five",
"id": "5"
}, {
"name": "six",
"id": "6"
}, {
"name": "seven",
"id": "7"
}]
$scope.showFn = function(Item) {
$scope.shownId = Item;
$scope.showPopup = true;
$timeout(function() {
console.log("timeout");
$scope.showPopup = false;
}, 1000);
};
});
Related
I want to set my angular chosen with default value from my response. also my Angular chosen dropdown values also coming from AJAX response. I tried ng-init and pointing the value with respect to index. But no luck.
HTML
<select ng-init="model.country = cities[currentLocationIdx]"
chosen ng-model="model.country"
ng-options=" cities.name for cities in cities" required>
<option value="">Select a Location</option>
</select>
JS:
$scope.model.country = "Bangalore";
$scope.currentLocationIdx = $scope.cities.findIndex( city => city.name === $scope.model.country );
JSON:
[
{
"name": "South Andaman"
},
{
"name": "Nicobar"
},
{
"name": "Adilabad"
},
{
"name": "Anantapur"
},
{
"name": "Chittoor"
},
{
"name": "East Godavari"
},
{
"name": "Bangalore"
}
]
You just need to declare your variable as obj in controller like this:
$scope.model = {};
WORKING DEMO
Try this below updated code. Its working at my end with chosen library.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body ng-app="app" ng-controller="ctrl">
<select name="mySelect" id="mySelect" chosen
ng-options="city.name for city in cities track by city.name"
ng-model="country"></select>
{{country}}
<script src="../lib/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-chosen-localytics/1.8.0/angular-chosen.js"></script>
<script>
var app = angular.module('app', []);
app.controller('ctrl', function ($scope) {
$scope.cities = [
{
"name": "South Andaman"
},
{
"name": "Nicobar"
},
{
"name": "Adilabad"
},
{
"name": "Anantapur"
},
{
"name": "Chittoor"
},
{
"name": "East Godavari"
},
{
"name": "Bangalore"
}
];
$scope.country = { "name": "Bangalore" };
});
</script>
</body>
</html>
Response code :
In this response eid is repeated, but I want to dispaly only once.
{"response": [
{
"sid": 1,
"eid": "AA",
"ename": "AA11"
},{
"sid": 2,
"eid": "AA",
"ename": "AA11"
}
],
"status": "success"
}
You could use the unique filter from AngularUI
<p ng-repeat="x in data.response | unique: 'ename'">{{x.ename}}</p>
DEMO
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/angular-ui/0.4.0/angular-ui.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="myCtrl">
<p ng-repeat="x in data.response | unique: 'ename'">{{x.ename}}</p>
<script>
//App declaration
var app = angular.module('myApp',['ui.filters']);
//Controller Declaration
app.controller('myCtrl',function($scope){
$scope.data = {"response": [
{
"sid": 1,
"eid": "AA",
"ename": "AA11"
},{
"sid": 2,
"eid": "AA",
"ename": "AA11"
}
],
"status": "success"
};
});
</script>
</body>
</html>
There is no magic way. This task should primarily be completed before the response lands the client (on server).
What you can do is make a function which handles the response the way you prefer.
e.g.
//Removes duplicates of eid property
function getUniqueValues(input) {
var output = [];
function existsInOutput(element) {
return output.map(function(val) {
return val.eid
}).includes(element.eid)
};
angular.forEach(input,function(val, key) {
if (!existsInOutput(val)) {
output.push(val);
}
})
return output;
}
I would like to update document in a JSON Collection using AngularJS
My JSON Collection:
$Scope.employee = {
"staff" :
[
{
"id" : 1,
"Name" : "John",
"email" : "john#abc.com"
},
{
"id" : 2,
"Name" : "Watson",
"email" : "watson#abc.com"
},
{
"id" : 3,
"Name" : "jack",
"email" : "jack#abc.com"
},
{
"id" : 4,
"Name" : "Jim",
"email" : "jim#abc.com"
},
{
"id" : 5,
"Name" : "Rose",
"email" : "rose#abc.com"
}
]
};
Now I need to update the document where Id = 2 to
$Scope.updateEmployee = {
"id" : 2,
"Name": "Emma",
"email": "emma#abc.com"
};
Kindly assist me how to replace a particular document and I would like to update the email of id = 5 to hr#abc.com
You can do this,
$scope.update = function(){
$scope.employee.staff.forEach(function (item) {
if (item.id == 2 ) {
item.Name = "Emma";
item.email ="emma#abc.com";
};
});
}
DEMO
$scope.updateItem = function(item) {
for (var i = 0; i < $cope.employee.staff.length; i++) {
if (item.id === $scope.employee.staff[i].id) {
$scope.employee.staff[i] = item;
break;
}
}
}
Now if you want to update $Scope.employee with id 5, just do :
$scope.updateItem({
id: 5,
Name: 'bill',
email: 'test#test.fr'
});
You can do it using underscore.js
Plunker
Basically, you should refrain from traversing your entire list because this can cause some performance related issues. What underscore.js will do is that it will return as soon as it finds an acceptable element, and doesn't traverse the entire list.
Read the official documentation here
find_.find(list, predicate, [context]) Alias: detect
Looks through each value in the list, returning the first one that passes a
truth test (predicate), or undefined if no value passes the test. The
function returns as soon as it finds an acceptable element, and
doesn't traverse the entire list.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.employee = {
"staff": [{
"id": 1,
"Name": "John",
"email": "john#abc.com"
}, {
"id": 2,
"Name": "Watson",
"email": "watson#abc.com"
}, {
"id": 3,
"Name": "jack",
"email": "jack#abc.com"
}, {
"id": 4,
"Name": "Jim",
"email": "jim#abc.com"
}, {
"id": 5,
"Name": "Rose",
"email": "rose#abc.com"
}]
};
$scope.update = function() {
var index = _.findIndex($scope.employee.staff, function(o) {
return o.id == 2;
})
$scope.employee.staff[index].Name = "Emma";
$scope.employee.staff[index].email = "emma#abc.com";
}
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('
<base href="' + document.location + '" />');
</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="emp in employee.staff ">
<div>{{emp.id}} {{emp.Name}}</div>
</div>
<button ng-click="update()">
Update
</button>
</body>
</html>
I'm trying to populate a Select getting data from a webapi using ng-options.
Basically, my webapi returns the following JSON:
{
"items":[
{
"name":"X",
"id":1
},
{
"name":"Y",
"id":2
}
]
}
And I Need to generate options in a select displaying the name property, but with the id as value.
The problem is that I can't display my options using ng-options. Here's what I'm trying:
<html ng-app='app'>
<head>
<title>angular</title>
</head>
<body ng-controller='DemoCtrl'>
<select ng-model="selectedTestAccount" ng-options="option.name for option in testAccounts">
<option value="">Select Account</option>
</select>
<script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
<script>
angular.module('app', []).controller('DemoCtrl', function ($scope, $http) {
$scope.selectedTestAccount = null;
$scope.testAccounts = [];
$http({
method: 'GET',
url: '/api/values',
data: {}
}).success(function (result) {
console.log(result);
$scope.testAccounts = JSON.parse(result.items);
});
});
</script>
</body>
</html>
I hope this helps you
angular.module("app", []);
angular.module("app").controller("ctrl", function($scope) {
$scope.testAccounts = [];
var youJson = [
{ "items": [{ "name": "X", "id": "your value for X" }, { "name": "Y", "id": "your value for Y" }] },
{ "items": [{ "name": "A", "id": "your value for A" }, { "name": "B", "id": "your value for B" }] }
];
angular.forEach(youJson, function(items) {
angular.forEach(items.items, function(item) {
$scope.testAccounts.push(item);
});
});
console.log($scope.testAccounts);
});
<!doctype html>
<html ng-app="app" ng-controller="ctrl">
<head>
</head>
<body>
<select ng-model="mySelect" ng-options="item.id as item.name for item in testAccounts"></select>
{{mySelect}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
</body>
</html>
I am a bit noob to backbone JS
I have this one code in which I need to list out the categories according to the json and list them out on the page.
Now when user clicks on any of the category list a new JSON attached to that category is fetched from the server and listed on the page.
My problem is I have listed out the categories but don't know how to get new JSON and display it on the screen by creating views and collection for new JSON dynamically depending on thecategory chosen.
Here is my HTML Code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Category list</title>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.1/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Category list</h1>
<hr />
<div class='categoryList'></div>
<div class='selected_category'></div>
</div>
<script type="text/template" id="events-template">
<% _.each( CategoryCollection, function(Category){ %>
<div class='category'>
<h2 class='<%= Category.get("category") %>' >
<%= Category.get("category") %>
</h2>
</div>
<% }); %>
</script>
<script type="text/template" id="selectedCategory-template">
<% _.each( SelectedCategoryCollection, function(selected_category){ %>
<div class='category_list'>
<%= selected_category.get("category") %>
</div>
<% }); %>
</script>
</body>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.2/underscore-min.js" type="text/javascript"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/backbone.js/0.9.2/backbone-min.js"></script>
<script>
var categoryJSON;
var Category = Backbone.Model.extend();
var CategoryCollection = Backbone.Collection.extend({
model: Category,
url: 'categories.json',
parse: function (response) {
categoryJSON = response;
console.log(categoryJSON)
return response;
}
});
var CategoryAbout = Backbone.View.extend ({
el: '.categoryList',
render: function () {
var that = this;
// console.log(that)
var eventCategory = new CategoryCollection();
// console.log(eventCategory);
eventCategory.fetch({
success: function (CategoryCollection) {
// console.log(CategoryCollection)
var template = _.template($('#events-template').html(), {CategoryCollection: CategoryCollection.models});
// console.log(template)
that.$el.html(template);
}
})
},
events: {
"click .category h2" : "doSearch"
},
doSearch: function(event){
// Button clicked
console.log('clicked');
console.log(event.toElement.className)
router.navigate('/category/'+event.toElement.className, { trigger: true });
// window.location.href = window.location.href + '/#/category/all';
}
});
var CategoryAbout = new CategoryAbout ();
var Router = Backbone.Router.extend({
routes: {
'': 'home',
"category/:categoryName": "getCategory",
}
});
var router = new Router();
// console.log(router)
router.on('route:home', function () {
// console.log(this)
console.log('home');
CategoryAbout.render();
});
router.on('route:getCategory', function (categoryName) {
console.log( "Category Name " + categoryName );
var urlToFetch;
for (var i = 0; i < categoryJSON.length; i++) {
if(categoryJSON[i].category == categoryName)
{
urlToFetch = categoryJSON[i].data;
}
};
console.log(urlToFetch);
});
Backbone.history.start();
</script>
and the JSON file for Category
[
{
"category": "all",
"data": "all.json"
},
{
"category": "music",
"data": "music.json"
},
{
"category": "business",
"data": "business.json"
},
{
"category": "sports",
"data": "sports.json"
},
{
"category": "workshops",
"data": "workshops.json"
}
]
and say that we have chosen workshop category then JSON of workshop is like this
{
"request": {
"venue": "0",
"ids": "0",
"type": "json",
"city": "NY",
"edate": 0,
"page": 0,
"keywords": "0",
"sdate": 0,
"category": "workshops",
"city_display": "NY",
"rows": 50
},
"count": 10,
"item": [
{
"event_id": "230801950442480",
"eventname": "Holiday special YES! course :) :)",
"thumb_url": "http://graph.facebook.com/230801950442480/picture",
"thumb_url_large": "http://graph.facebook.com/230801950442480/picture?type=large",
"start_time": 1395943200,
"start_time_display": "Thu Mar 27 2014 at 06:00 pm",
"end_time": 1396213200,
"end_time_display": "Sun Mar 30 2014 at 09:00 pm",
"location": "NY,ABC street",
"venue": {
"street": "",
"city": "NY",
"state": "XYZ",
"country": "PQR"
},
"label": "Tomorrow",
"featured": 0
},
{
"event_id": "230801950442480",
"eventname": "Holiday special YES! course :) :)",
"thumb_url": "http://graph.facebook.com/230801950442480/picture",
"thumb_url_large": "http://graph.facebook.com/230801950442480/picture?type=large",
"start_time": 1395943200,
"start_time_display": "Thu Mar 27 2014 at 06:00 pm",
"end_time": 1396213200,
"end_time_display": "Sun Mar 30 2014 at 09:00 pm",
"location": "NY,ABC street",
"venue": {
"street": "",
"city": "NY",
"state": "XYZ",
"country": "PQR"
},
"label": "Tomorrow",
"featured": 0
}
]
}
thanks in advance.
let me know if I am missing out any data