is data a reserved keyword in angularjs? - angularjs

The code below doesn't work if I use data in lst, it works, if I replace data with x, so is data a reserved keyword in AngularJS and why?
<script src="http://ajadata.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app='app1'>
<div id='Grocery' ng-controller='Grocery'>
<h3>Grocery List</h3>
<div ng-repeat='data in lst'>
<h4>{{data.item}}</h4>
</div>
<br>
<p> enter item:
<input type="text" ng-model='addItem' />
</p>
<button ng-click='addTolist(addItem)'>Add to list</button>
<button ng-click='addTolist(addItem)'>Add to list</button>
<h2>{{NoItemError}}</h2>
</div>
<!-- End of Grocery -->
<script>
var app1 = angular.module('app1', []);
app1.controller('Grocery', function($scope) {
$scope.lst = [{
item: 'banana',
needed: false
},
{
item: 'apple',
needed: false
},
{
item: 'milk',
needed: false
},
{
item: 'tomato',
needed: false
},
{
item: 'juice',
needed: false
}
]
$scope.addTolist = function(addItem) {
if (!(addItem === undefined || addItem === '')) {
$scope.lst.push({
item: addItem,
needed: false
});
$scope.NoItemError = '';
} else {
$scope.NoItemError = 'Please enter an item';
}
}
});
</script>
</body>

While replacing text with another, you broke your CDN URL for the AngularJS script.
It became http://ajadata.googleapis.com
Change it to http://ajax.googleapis.com
Here is a full script:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
And here is a working example of your code:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app='app1'>
<div id='Grocery' ng-controller='Grocery'>
<h3>Grocery List</h3>
<div ng-repeat='data in lst'>
<h4>{{data.item}}</h4>
</div>
<br>
<p> enter item:
<input type="text" ng-model='addItem' />
</p>
<button ng-click='addTolist(addItem)'>Add to list</button>
<button ng-click='addTolist(addItem)'>Add to list</button>
<h2>{{NoItemError}}</h2>
</div>
<!-- End of Grocery -->
<script>
var app1 = angular.module('app1', []);
app1.controller('Grocery', function($scope) {
$scope.lst = [{
item: 'banana',
needed: false
},
{
item: 'apple',
needed: false
},
{
item: 'milk',
needed: false
},
{
item: 'tomato',
needed: false
},
{
item: 'juice',
needed: false
}
]
$scope.addTolist = function(addItem) {
if (!(addItem === undefined || addItem === '')) {
$scope.lst.push({
item: addItem,
needed: false
});
$scope.NoItemError = '';
} else {
$scope.NoItemError = 'Please enter an item';
}
}
});
</script>
</body>
Most reserved words in AngularJS start with $, for example $index or $id, etc.

Related

angular radio button set checked

i have multiple radio button groups
i need to set one of each group (maybe none) as selected
datasource
html Code
<div class='row' ng-show="mk.selectedTypeAttributesID.length != 0">
<div class='col-xs-6 col-sm-6 col-md-6 col-lg-6' ng-repeat="att in selectedTypeAttributesID">
<div class="switch-field">
<div class="switch-title">{{att.name}}</div>
<div>
<input ng-repeat-start="val in att.Values" class="bttn-input" type="radio" id="switch_{{val.val}}" name="switch_{{att.id}}" value="{{val.val}}" ng-click="mk.AttChange(att.id,val.val)" />
<label ng-repeat-end class="bttn-input" for="switch_{{val.val}}">{{val.val}}</label>
</div>
</div>
</div>
</div>
i need to use the value of 'Selected' On the datasource to set the checkbox
source Update
You need to use ng-model to select the radio button..
Where ng-model holds the selected value as shown below.
$scope.options = [{Selected: false, val: "red"}, {Selected: true, val:"Black"}, {Selected: false, val:"Pink"}];
$scope.selected = undefined;
var findResult = $scope.options.find(function(x){ return x.Selected == true });
if(findResult){
$scope.selected = findResult.val;
}
Here's a JSFiddle
Edit: Since the sources of the checkboxes are dynamic then build a dynamic selection tree for modal to bind to..
Here's an example:
$scope.options = [{ 0 : [{Selected: false, val: "red"}, {Selected: true, val:"Black"}, {Selected: false, val:"Pink"}]}, { 1 : [{ Selected: false, val: "2" }, { Selected: true, val: "1" }]}];
$scope.choices = [];
for(var i = 0; i < Object.keys($scope.options).length; i++){
var keys = Object.keys($scope.options);
$scope.choices.push({ Id: keys[i], Value: $scope.options[i][keys[i]].find(function(x){ return x.Selected == true }).val });
}
JSFiddle
Are you looking for a solution like so?
var app = angular.module('myApp', []);
app.controller('MyController', function MyController($scope) {
$scope.selectedTypeAttributesID = [{
id: 1,
Values: [{
val: "red",
selected: ""
}, {
val: "green",
selected: ""
}, {
val: "blue",
selected: ""
}]
},
{
id: 2,
Values: [{
val: "1",
selected: ""
}, {
val: "2",
selected: ""
}, {
val: "3",
selected: ""
}]
}
];
$scope.setVal = function(att, index, val) {
for (var k of att.Values) {
k.selected = "";
}
att.Values[index].selected = val;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller='MyController' ng-app="myApp">
<div class='row'>
<div class='col-xs-6 col-sm-6 col-md-6 col-lg-6' ng-repeat="att in selectedTypeAttributesID">
<div class="switch-field">
<div class="switch-title">{{att.name}}</div>
<div>
<input ng-repeat-start="val in att.Values" class="bttn-input" type="radio" id="switch_{{val.val}}" name="switch_{{att.id}}" ng-value="val.val" ng-click="setVal(att, $index, val.val)" />
<label ng-repeat-end class="bttn-input" for="switch_{{val.val}}">{{val.val}}</label>
</div>
</div>
</div>
</div>
<pre>{{selectedTypeAttributesID | json}}</pre>
</div>

ng-model into ng-repeat Angularjs

I'm asking if is possible to do something as that in angular
<div ng-app="app">
<div ng-controller="mainController">
<ul ng-repeat="movie in movies |searchFilter:Filter.genre | searchFilter:Filter.name |searchFilter:Filter.pic ">
<li>{{movie.name}}</li>
</ul>
<h2>genre</h2>
<div>
<label>Comedy </label><input type="checkbox" ng-model="Filter.genre.Comedy" ng-true-value="Comedy" data-ng-false-value=''/><br/>
</div>
<h2>PIC</h2>
<label>aa</label><input type="checkbox" ng-model="Filter.pic.aa" ng-true-value="ciao" data-ng-false-value=''/><br/>
<h2>Name</h2>
<label>Shrek</label><input type="checkbox" ng-model="Filter.name.Shrek" ng-true-value="The God" data-ng-false-value=''/><br/>
</div>
</div>
i'm creating a checkbox for filter on different fields (size,name,genre)
ill have a list of avaible sizes,names and genres .
The issue is on ng-model and i tried to write it as "Filter.genre.genre.name" or
"Filter["genre"+genre.name]" and also "Filter.genre[genre.name]" but still not work .
the js.file is
var app =angular.module('app', []);
app.controller('mainController', function($scope) {
$scope.movies = [{name:'Shrek', genre:'Comedy',pic:"cc"},
{name:'Die Hard', genre:'Comedy',pic:"aa"},
{name:'The Godfather', genre:'Drama',pic:"ciao"},
{name:'The Godher', genre:'Comedy',pic:"lel"}];
$scope.genres = [{name:"Comedy"},{name:"Action"},{name:"Drama"}];
});
app.filter('searchFilter',function($filter) {
return function(items,searchfilter) {
var isSearchFilterEmpty = true;
//searchfilter darf nicht leer sein
angular.forEach(searchfilter, function(searchstring) {
if(searchstring !=null && searchstring !=""){
isSearchFilterEmpty= false;
}
});
if(!isSearchFilterEmpty){
var result = [];
angular.forEach(items, function(item) {
var isFound = false;
angular.forEach(item, function(term,key) {
if(term != null && !isFound){
term = term.toLowerCase();
angular.forEach(searchfilter, function(searchstring) {
searchstring = searchstring.toLowerCase();
if(searchstring !="" && term.indexOf(searchstring) !=-1 && !isFound){
result.push(item);
isFound = true;
// console.log(key,term);
}
});
}
});
});
return result;
}else{
return items;
}
}
});
if i make 3 different labels for the field Comedy, Action and Drama with ng-models called as
ng-model="Filter.genre.Comedy" ; ng-model="Filter.genre.Action" and ng-model="Filter.genre.Drama"
it work but it doesnt work if i try to write it into ng-repeat . I hope to have been clearer
In this sample i try to handle your question by change the Model of your page.
we have:
list of movies array => $scope.movies = []
dynamic filters array => $scope.genres = [], $scope.years = [] or more
our target:
Create a dynamic filters to search in movies
what we do
$scope.filterHandler = function (key, value) {}
Run when user start searching on input or select, this function help us to create a filter as object by sending key and value which result is {key:value}
$scope.searchTypeHandler = function (type, dependTo) {}
Run when our filters has some array for example genre has genres as dropdown select, this function help us to return the array which depend to the filter.
var app = angular.module("app", []);
app.controller("ctrl", [
"$scope",
function($scope) {
//your options
$scope.movies = [{
name: 'Shrek',
genre: 'Comedy',
year: 2000
},
{
name: 'Die Hard',
genre: 'Action',
year: 2000
},
{
name: 'The Godfather',
genre: 'Drama',
year: 2015
},
{
name: 'The Godher',
genre: 'Comedy',
year: 2017
}
];
$scope.genres = [{
name: "Comedy"
},
{
name: "Action"
},
{
name: "Drama"
}
];
$scope.years = [{
name: 2000
},
{
name: 2015
},
{
name: 2017
}
];
//
$scope.filter = {}
$scope.filterHandler = function(key, value) {
var object = {};
object[key] = value;
$scope.filter["find"] = object;
};
$scope.searchTypeHandler = function(type, dependTo) {
$scope.filter = {};
$scope.filter.searchType = type;
$scope.filter.options = undefined;
if (dependTo != null) {
$scope.filter.options = $scope[dependTo];
}
};
//default
$scope.searchTypeHandler("name");
}
]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="container" ng-app="app" ng-controller="ctrl">
<div class="page-header">
<div class="row">
<div class="col-lg-12">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<h4>Movies</h4>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6 pull-right">
<div class="input-group">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
By {{filter.searchType}}
<span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-left">
<li><a ng-click="searchTypeHandler('genre', 'genres')">Filter By Genre</a></li>
<li><a ng-click="searchTypeHandler('name', null)">Filter By Name</a></li>
<li><a ng-click="searchTypeHandler('year', 'years')">Filter By Year</a></li>
</ul>
</div>
<input ng-hide="filter.options" type="text" class="form-control" ng-model="filter.query" ng-change="filterHandler(filter.searchType, filter.query)">
<select ng-show="filter.options" class="form-control" ng-model="filter.option" ng-change="filterHandler(filter.searchType, filter.option)" ng-options="option.name as option.name for option in filter.options"></select>
</div>
<!-- /input-group -->
</div>
</div>
</div>
</div>
<ul class="list-group">
<li class="list-group-item" ng-repeat="movie in movies | filter: filter.find">
{{movie.name}} - <label class="label label-info">Ggenre: {{movie.genre}}</label> - <label class="label label-default">Year: {{movie.year}}</label>
</li>
</ul>
</div>

Dynamic Value Checkbox Vuejs 2

I can't get the value of the checkbox.
<li v-for="mainCat in mainCategories">
<input type="checkbox" :value="mainCat.merchantId" v-model="mainCategories.merchantId" id="mainCat.merchantId" #click="merchantCategoryId">
</li>
My Methods:
methods: {
merchantCategoryId: function() {
console.log(this.mainCategories.merchantId)
}
}
When it clicks I only get true and false for uncheck. TY
<div id="demo" >
<ul>
<li v-for="mainCat in mainCategories">
<input type="checkbox" :value="mainCat.merchantId" :id="mainCat.merchantId" v-model="checkedCategories" #click="check($event)"> {{mainCat.merchantId}}
</li>
</ul>
{{ checkedCategories }}
</div>
And in your script:
var demo = new Vue({
el: '#demo',
data: {
checkedCategories: [],
mainCategories: [{
merchantId: '1'
}, {
merchantId: '2'
}]
},
methods: {
check: function(e) {
if (e.target.checked) {
console.log(e.target.value)
}
}
}
})
Check this: https://v2.vuejs.org/v2/guide/forms.html#Checkbox
Working fiddle: http://jsfiddle.net/yMv7y/9206/
new Vue({
el: '#app',
data() {
return {
mainCategory: {
merchantIds: []
},
mainCategories: [{
merchantId: 1,
category: 'first category'
},
{
merchantId: 2,
category: 'second category'
}]
}
},
methods: {
merchantCategoryId: function() {
console.log(this.mainCategory.merchantIds)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<li v-for="mainCat in mainCategories">
<input type="checkbox"
:value="mainCat.merchantId"
v-model="mainCategory.merchantIds"
id="mainCat.merchantId"
#click="merchantCategoryId">
</li>
</div>
OR
new Vue({
el: '#app',
data() {
return {
mainCategories: [{
merchantId: 1,
category: 'first category'
},
{
merchantId: 2,
category: 'second category'
}]
}
},
methods: {
merchantCategoryId: function(event) {
console.log(event.target.value, event.target.checked)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<li v-for="mainCat in mainCategories">
<input type="checkbox"
:value="mainCat.merchantId"
id="mainCat.merchantId"
#change="merchantCategoryId($event)">
</li>
</div>
1.I observed both the mainCategories and v-model value v-model="mainCategories.merchantId" are the same.
You cannot access the marchantId of mainCategories, this is the mistake what you did apart from that nothing is wrong in the code sample to get the value of marchantId.
2 When your using $event in the click or change event function no need to use the v-model value.

Deselect a selected row in ng-repeat

How do I deselect a row that I have just selected using the same button that I have used to select and highlight the row from an ng-repeat list? What different options are there, does anyone have any examples or links as I can't find any?
EDIT:-
Please see Plunker using link
https://plnkr.co/edit/LYrmpLUwGaWx8wLeCOoT
code is here:-
html
<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.12/angular.js" data-semver="1.4.9"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<div ng-repeat="item in items" ng-class="{sel: item.Item == selected}">
<label>Item No. {{item.Item}}</lablel> |
<label>{{item.Description}}</label> |
<button ng-click="onClick(item.Item);" class="btn btn-primary">
{{item.Item == selected ? 'Hide' : 'Show'}}
</button>
</div>
<br />
<br />
<div ng-switch="moduleState">
<div ng-switch-when="details">
These are your details:-
Item {{selected}} is selected
</div>
</body>
</html>
app.js
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{
Item: 1,
Description: 'This is item 1'
},
{
Item: 2,
Description: 'This is item 2'
},
{
Item: 3,
Description: 'This is item 3'
}
];
$scope.onClick = function (item) {
$scope.selected = item;
$scope.moduleState = 'details';
};
});
Once one of the buttons is selected how do I deselect it again?
$scope.onClick = function(item) {
if ($scope.selected === item) {
$scope.selected = null;
}
else {
$scope.selected = item;
}
};
And in the view:
<div ng-repeat="item in items" ng-class="{sel: item.Item == selected}">
<label>Item No. {{item.Item}}</lablel> |
<label>{{item.Description}}</label> |
<button ng-click="onClick(item.Item);" class="btn btn-primary">
{{item.Item == selected ? 'Hide' : 'Show'}}
</button>
</div>
<br />
<br />
<div ng-if="selected">
These are your details:-
Item {{ selected }} is selected
</div>
Check the plunkr below:
https://plnkr.co/edit/u7I9nIRZgOMB7vqBr92n?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
{
Item: 1,
isVisible: false,
Description: 'This is item 1'
},
{
Item: 2,
isVisible: false,
Description: 'This is item 2'
},
{
Item: 3,
isVisible: false,
Description: 'This is item 3'
}
];
$scope.onClick = function (item) {
if(!item.isVisible) {
item.isVisible = !item.isVisible;
$scope.selected = item.Item;
$scope.moduleState = 'details';
} else {
item.isVisible = !item.isVisible;
$scope.selected = $scope.moduleState = "";
}
};
});
<button ng-click="onClick(item);" class="btn btn-primary">
{{item.Item == selected ? 'Hide' : 'Show'}}
</button>
Basically what i did is:
Added a flag "isVisible" for each row
Toggled the flag when its set to visible
on second click, if its visible, hide it.

How to filter first letter in a button using AngularJS

How to make the button functional, and the button has default value, for example button A-B has a range for a to b of first letter to be filter. Thanks, Sorry for my last post, it was hard to understand. =)
var app = angular.module('app', []);
app.filter('startsWithLetter', function () {
return function (items, letter) {
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.name.substring(0, 1))) {
filtered.push(item);
}
}
return filtered;
};
});
app.controller('PersonCtrl', function () {
this.friends = [{
name: 'Andrew'
}, {
name: 'Baldo'
}, {
name: 'Carlo'
}, {
name: 'Delo'
}, {
name: 'Emman'
}, {
name: 'Ferman'
}];
});
</style>
<script src="//code.angularjs.org/1.3.0-beta.7/angular.js"></script>
<style>
<div ng-app="app">
<div ng-controller="PersonCtrl as person">
<input type="text" ng-model="letter" placeholder="Enter a letter to filter">
<button>A-B</button>
<button>C-D</button>
<button>E-F</button>
<ul>
<li ng-repeat="friend in person.friends | startsWithLetter:letter">
{{ friend }}
</li>
</ul>
</div>
</div>
Is this what you meant? Did you want clicking each button to filter by those 2 letters?
All I changed was set the markup for the buttons to be:
<button ng-click="letter='[AB]'">A-B</button>
<button ng-click="letter='[CD]'">C-D</button>
<button ng-click="letter='[EF]'">E-F</button>
var app = angular.module('app', []);
app.filter('startsWithLetter', function () {
return function (items, letter) {
var filtered = [];
var letterMatch = new RegExp(letter, 'i');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (letterMatch.test(item.name.substring(0, 1))) {
filtered.push(item);
}
}
return filtered;
};
});
app.controller('PersonCtrl', function () {
this.friends = [{
name: 'Andrew'
}, {
name: 'Baldo'
}, {
name: 'Carlo'
}, {
name: 'Delo'
}, {
name: 'Emman'
}, {
name: 'Ferman'
}];
});
</style>
<script src="//code.angularjs.org/1.3.0-beta.7/angular.js"></script>
<style>
<div ng-app="app">
<div ng-controller="PersonCtrl as person">
<input type="text" ng-model="letter" placeholder="Enter a letter to filter">
<button ng-click="letter='[AB]'">A-B</button>
<button ng-click="letter='[CD]'">C-D</button>
<button ng-click="letter='[EF]'">E-F</button>
<ul>
<li ng-repeat="friend in person.friends | startsWithLetter:letter">
{{ friend }}
</li>
</ul>
</div>
</div>

Resources