ng-change Doesn't work - javascript

My code doesn't work, but it is very simple, i copied from an example (http://www.tilcode.com/angularjs-infinite-list-tutorial/):
HTML:
<div class="form-group">
<label>Produtos: </label>
<div>
<li data-ng-repeat="produto in prodPromocao track by $index">
<input name="product" type="text" data-ng-model="prodPromocao[$index]" data-ng-change="addProd($index)" class="form-control">
<a href="" data-ng-show="produto" data-ng-click="prodPromocao.splice($index,1)">
[Remove]</a>
</li>
</div>
Controller:
$scope.prodPromocao = [''];
var addProd = function (index) {
console.log(index);
if (index == $scope.prodPromocao.length - 1) {
$scope.prodPromocao.push('');
}
}
Actually, this function addProd is not even called.

Your ng-change function should be defined on $scope
$scope.addProd = function (index) {
console.log(index);
if (index == $scope.prodPromocao.length - 1) {
$scope.prodPromocao.push('');
}
}

$scope.prodPromocao = [''];
$scope.addProd = function (index) {
console.log(index);
if (index === $scope.prodPromocao.length - 1) {
$scope.prodPromocao.push('');
}
}

Related

How to merge load event and change event in javascript under one function?

My html code for one bundle of checkboxes. i have some bundle of checkboxes like this with different class names. I have shown one bundle here.
<ul>
<li><input class="TestAll" type="checkbox" id="select_all"/> Selecct All</li>
<li><input class="Test" type="checkbox"> This is Item 1</li>
<li><input class="Test" type="checkbox"> This is Item 2</li>
<li><input class="Test" type="checkbox"> This is Item 3</li>
<li><input class="Test" type="checkbox"> This is Item 4</li>
<li><input class="Test" type="checkbox"> This is Item 5</li>
<li><input class="Test" type="checkbox"> This is Item 6</li>
</ul>
My javascript is shown below
<script type="text/javascript">
function Selection(id, name) {
var ALL = document.getElementById(id);
var Single = document.getElementsByClassName(name);
ALL.addEventListener("change", function (e) {
for (i = 0; i < Single.length; i++) {
Single[i].checked = ALL.checked;
}
});
for (var i = 0; i < Single.length; i++) {
Single[i].addEventListener('change', function (e) {
if (this.checked == false) {
ALL.checked = false;
}
if ($('.' + name + ':checkbox:checked').length == Single.length) {
ALL.checked = true;
}
});
}
}
// window.onload = Selection;
</script>
here i'm taking the id of the select All checkbox and classname for other checkboxes
<script type="text/javascript">
Selection('select_all', 'Test');
</script>
This function is for the create page. the following function is for edit page.
function SelectionOnLoad(id, name) {
var all = document.getElementById(id);
var single = document.getElementsByClassName(name);
if ($('.' + name + ':checkbox:checked').length == single.length) {
all.checked = true;
}
else {
all.checked = false;
}
}
$(document).ready(function () {
SelectionOnLoad('select_all', 'Test');
});
Is there any ways to do these separated functions under one function ... Any suggestions ?
If I understand you mean correctly, you may want to use this function:
function selectionOnload(id, name) {
var all = document.getElementById(id);
var single = document.getElementsByClassName(name);
if ($('.' + name + ':checkbox:checked').length == single.length) {
all.checked = true;
}
all.addEventListener("change", function(e) {
for (i = 0; i < single.length; i++) {
single[i].checked = all.checked;
}
});
for (var i = 0; i < single.length; i++) {
single[i].addEventListener('change', function(e) {
if ($('.' + name + ':checkbox:checked').length == single.length) {
all.checked = true;
} else {
all.checked = false;
}
});
}
};
$(document).ready(function() {
selectionOnload('select_all', 'Test');
});
Tip: We just need to check all of the checkboxes are checked or not 1 time. If they are, set checked attribute to all. Otherwise, it will be false.
And we can also write the events inside the selectionOnload function/

How to apply multiple filters with pagination in Angular JS?

I am trying to apply multiple filters with pagination in Angular JS i am able to paginate the results with one filter but whenever there is multiple filters i am unable do it OR is performing among two filters instead of AND please help me to achieve this any help will be greatly appreciated. here is my code.
Here is my index.html
<html xmlns:ng="http://angularjs.org" ng-app lang="en">
<head>
<meta charset="utf-8">
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.1.1/css/bootstrap.no-icons.min.css" rel="stylesheet">
<link href="http://netdna.bootstrapcdn.com/font-awesome/2.0/css/font-awesome.css" rel="stylesheet">
<script src="http://code.angularjs.org/1.1.0/angular.min.js"></script>
</head>
<body>
</div>
<div ng-controller="ctrlRead">
<div class="input-append">
<input type="text" ng-model="name" ng-change="nameSearch()" class="input-large search-query" placeholder="Search Name">
<input type="text" ng-model="country" ng-change="countrySearch()" class="input-large search-query" placeholder="Search Name">
<span class="add-on"><i class="icon-search"></i></span>
</div>
<div class="pagination pull-right">
<ul>
<li ng-class="{disabled: currentPage == 0}">
<a href ng-click="prevPage()">« Prev</a>
</li>
<li ng-repeat="n in range(pagedItems.length)"
ng-class="{active: n == currentPage}"
ng-click="setPage()">
<a href ng-bind="n + 1">1</a>
</li>
<li ng-class="{disabled: currentPage == pagedItems.length - 1}">
<a href ng-click="nextPage()">Next »</a>
</li>
</ul>
</div>
</div>
</body>
</html>
And here is my script.
function ctrlRead($scope, $filter) {
// init
$scope.sortingOrder = sortingOrder;
$scope.reverse = false;
$scope.filteredItems = [];
$scope.groupedItems = [];
$scope.itemsPerPage = 5;
$scope.pagedItems = [];
$scope.currentPage = 0;
$scope.items = [
{"id":"1","name":"John","country":"usa"},
{"id":"2","name":"Peter",,"country":"London"}];
// init the filtered items
$scope.nameSearch = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
if(item.name.includes($scope.name)){
return true;
}
});
$scope.countrySearch = function () {
$scope.filteredItems = $filter('filter')($scope.items, function (item) {
if(item.country.includes($scope.country)){
return true;
}
});
$scope.currentPage = 0;
// now group by pages
$scope.groupToPages();
};
// calculate page in place
$scope.groupToPages = function () {
$scope.pagedItems = [];
for (var i = 0; i < $scope.filteredItems.length; i++) {
if (i % $scope.itemsPerPage === 0) {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)] = [ $scope.filteredItems[i] ];
} else {
$scope.pagedItems[Math.floor(i / $scope.itemsPerPage)].push($scope.filteredItems[i]);
}
}
};
$scope.range = function (start, end) {
var ret = [];
if (!end) {
end = start;
start = 0;
}
for (var i = start; i < end; i++) {
ret.push(i);
}
return ret;
};
$scope.prevPage = function () {
if ($scope.currentPage > 0) {
$scope.currentPage--;
}
};
$scope.nextPage = function () {
if ($scope.currentPage < $scope.pagedItems.length - 1) {
$scope.currentPage++;
}
};
$scope.setPage = function () {
$scope.currentPage = this.n;
};
// functions have been describe process the data for display
$scope.search();
};
ctrlRead.$inject = ['$scope', '$filter'];
Hope this will help you, I am using standard filter and 2 other drop downs through which I am doing filter in table.
HTML Code
<div>
<label>Associated Products:</label>
<div class="row">
<div class="col-md-6">
<div class="col-md-4 custom-select">
<div class="custom-select-text">{{selected}}</div>
<select class="form-control select-area c-corporate-contact-us-from-select-country country-lang-select" data-widget="custom-select"
(change)="onSelectProductLine($event)" [(ngModel)]="selected">
<option value="0">Select a product line</option>
<option *ngFor="let ProductLine of productLines" value={{ProductLine.categoryId}}>
{{ProductLine.title}}
</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="col-md-4 custom-select" *ngIf="edited">
<div class="custom-select-text">{{selectedProduct}}</div>
<select class="form-control select-area c-corporate-contact-us-from-select-country country-lang-select" data-widget="custom-select"
(change)="onSelectProduct($event)" [(ngModel)]="selectedProduct">
<option value="0">Select a product</option>
<option *ngFor="let Product of products" value={{Product.categoryId}}>
{{Product.title}}
</option>
</select>
</div>
</div>
</div>
</div>
<div class="example-header">
<mat-form-field>
<input matInput (page)="changePage($event)" (keyup)="applyFilter($event.target.value)" placeholder="Search Products based on Product Numbers or Description or Associate Products">
</mat-form-field>
</div>
JS Code
onSelectProductLine(args) {
if (args.target.value != 0)
this.edited = true;
else
this.edited = false;
this.dataservice.getProduct(args.target.value).subscribe(res => this.products = res);
this.selected = args.target.options[args.target.selectedIndex].text;
this.applyFilterTopLevelProduct(this.selected);
}
onSelectProduct(args) {
this.selectedProduct = args.target.options[args.target.selectedIndex].text;
this.applyFilterSecondLevelProduct(this.selectedProduct);
}
applyFilter(filterValue: string) {
debugger;
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.productNumbers + data.title + data.associatedProducts).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
applyFilterTopLevelProduct(filterValue: string) {
debugger;
if (filterValue == "Select a product line")
filterValue = "";
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.toplevelProduct).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
applyFilterSecondLevelProduct(filterValue: string) {
if (filterValue == "Select a product") {
filterValue = this.selected;
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.toplevelProduct).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
else {
filterValue = filterValue.trim(); // Remove whitespace
filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
this.dataSource.filterPredicate =
(data: IFUsApi, filter: string) => {
let searchStr = (data.associatedProducts).toLowerCase();
return searchStr.indexOf(filter.toLowerCase()) != -1;
}
this.dataSource.filter = filterValue;
}
}

Angularjs devade tags when user put comma

I have a case in which I need to divide tags when the user put a comma separation, for the moment the user can only add tags one by one, what I want to do is allows user to enter more than one tag in the input separated by a comma:
This is what I have now :
this is what I want to do :
what I have so far :
<div class="form-group">
<label>Mes centres d'intérêt</label>
<div class="input-group" style="margin-bottom: 8px;">
<input id="tagInsert" type="text" name="newTag" ng-model="newTag" ng-model-options="{debounce: 100}" typeahead="tag for tag in getTags($viewValue)" class="form-control" typeahead-loading="loadingTags" ng-keydown="addInterestOnEvent($event)" ng-disabled="interestLimit" autocomplete="off">
<span class="input-group-btn"><span class="btn btn-primary" ng-click="addInterest()" analytics-on="click" ng-disabled="interestLimit" analytics-event="Ajout Interet" analytics-category="Profil">Ajouter</span></span>
</div>
<p class="form__field__error" ng-show="interestLimit">Vous avez atteint la limite de 10 centres d'intérêt.</p>
<ul class="tags">
<li class="tag" ng-repeat="name in user.interests track by $index">{{ name }} <i class="icon-close" ng-click="removeInterest($index)" analytics-on analytics-event="Supprimer Interet" analytics-category="Profil"></i></li>
</ul>
</div>
My controller :
$scope.getTags = function (name) {
return $http.get('/api/tags/' + name.replace('/', '')).then(function (result) {
var tags = result.data;
for (var i = tags.length; i--; ) {
var tagName = tags[i].name;
if ($scope.user.interests.indexOf(tagName) !== -1) tags.splice(i, 1);
else tags[i] = tagName;
}
return tags;
});
};
$scope.removeInterest = function (id) {
$scope.interestLimit = false;
$scope.user.interests.splice(id, 1);
}
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value;
if (value.length) {
element.value = '';
if ($scope.user.interests.indexOf(value) === -1) {
$scope.user.interests.push(value);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
};
$scope.addInterestOnEvent = function (event) {
if (event.which !== 13) return;
event.preventDefault();
$scope.addInterest();
};
$scope.remove = function () {
$scope.confirmModal = Modal.confirm.delete(function () {
User.remove(function () {
submit = true;
Auth.logout();
$location.path('/');
});
})('votre compte');
};
You should split value with comma and do for loop.
Change "addInterest" function like this:
$scope.addInterest = function () {
if ($scope.interestLimit) return;
var element = $document[0].getElementById('tagInsert'),
value = element.value.split(',');
if (value.length) {
element.value = '';
for (var i = 0; i < value.length; i++) {
if ($scope.interestLimit) break;
if ($scope.user.interests.indexOf(value[i]) === -1) {
$scope.user.interests.push(value[i]);
$scope.interestLimit = $scope.user.interests.length === 10;
}
}
}
};
As far as I understand , you want to split text into string array by comma
Try this code please
<input id='tags' type="text" />
<input type="button" value="Click" onclick="seperateText()" />
<script>
function seperateText(){
var text= document.getElementById("tags").value;
var tags = text.split(',');
console.log(text);
console.log(tags);
}
</script>

How to add object which checked in array?

I have checkboxes in the application, When I click check-box , The object which I checked, is added in array. But When I click one more time checkbox (unchecked), The object is not removed in array.
How can I fix it ?
HTML Source:
<ion-list ng-repeat="option in question.SurveyOptions ">
<li class="item item-checkbox checkbox-royal ">
<label class="checkbox">
<input type="checkbox" ng-checked="MyAnswers.indexOf(option)!=-1" ng-click="toggleCheckAnswer({OptionId:option.Id,QuestionId:question.Id})">
</label>
<div class="item item-text-wrap">
{{option.OptionsName}}
</div>
</li>
</ion-list>
Controller:
$scope.MyAnswers = [];
$scope.toggleCheckAnswer = function(Answer) {
if ($scope.MyAnswers.indexOf(Answer) === -1) {
$scope.MyAnswers.push(Answer);
} else {
$scope.MyAnswers.splice($scope.MyAnswers.indexOf(Answer), 1);
}
};
In the function Answer include only OptionId and QuestionId.
How can I find index of {OptionId:1,QuestionId:1}?
Try like this
var index = $scope.MyAnswers.map(function(x) {
return x.OptionId + "#" + x.QuestionId;
}).indexOf(Answer.OptionId + "#" + Answer.QuestionId);
console.log(index);
You can't use indexOf to find objets in array you need to iterate over array:
$scope.toggleCheckAnswer=function(Answer) {
var index = -1;
for (var i=0; i<$scope.MyAnswers.length; ++i) {
var answer = $scope.MyAnswers[i];
if ($scope.MyAnswers[i].OptionId == Answer.OptionId &&
$scope.MyAnswers[i].QuestionId == Answer.QuestionId) {
index = 1;
break;
}
}
if (index === -1) {
$scope.MyAnswers.push(Answer);
} else {
$scope.MyAnswers.splice(index, 1);
}
};

Angularjs ng-repeat does not update after changing $scope variable

Hi I am new to Angularjs. I am changing the $scope variable on dropdown list selection. that scope variable is used for ng-repeat on div.
html code:
<div class="col-md-6" ng-repeat="model in FilteredModels | filter:{ModelText : '!All models'}:true">
<div class="well">
<div class="media">
<div class="media-object small"><i class="pp-car"></i></div>
<div class="media-body">
<div class="text-box">
<h3>{{model.ModelText}}</h3><span class="hr-small"></span>
</div>
<div class="dashboard-control clearfix">
<div class="simple-metric text-left sub-metric">
<div class="metric-title">Satisfaction score</div>
<div class="metric-number text-red">{{model.SatisfactionAvg | number:2}}</div>
</div>
<div class="simple-metric text-left sub-metric">
<div class="metric-title">Total interviews</div>
<div class="metric-number">{{model.TotalInterviews}}</div>
</div>
</div>
<ul class="list-standard">
<li> View interviews</li>
</ul>
</div>
</div>
</div>
</div>
angularjs code :
function filtermodelbyId() {
$scope.FilteredModels = [];
dataFactory.getModelIdByFilter($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
$scope.FilteredModelIds = result.data;
});
if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
for (var i = $scope.models.length - 1; i >= 0; i--) {
if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
$scope.FilteredModels.push($scope.models[i]);
}
}
}
}
}
On change of dropdown list this filtermodelbyId() function gets call and i am pushing new values but this gets reflected after the second change on dropdown list.
is there any better way to represent this.
Thanks.
Seems like you are not using $http in dataFactory.getModelIdByFilter .
try using
$scope.$apply(function(){
$scope.FilteredModelIds = result.data;
});
Or else you can use angular services to load data (Assuming that you are using jquery ajax.)
You need to write if after $scope.FilteredModelIds is set
dataFactory.getModelIdByFilter($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
$scope.FilteredModelIds = result.data;
if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
for (var i = $scope.models.length - 1; i >= 0; i--) {
if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
$scope.FilteredModels.push($scope.models[i]);
}
}
}
}
});
Just of quick wild guess:
function filtermodelbyId() {
$scope.FilteredModels = [];
dataFactory.getModelIdByFilter($scope.region, $scope.subregion).success($scope.handleSuccess).then(function (result) {
$scope.FilteredModelIds = result.data;
if ($scope.FilteredModelIds != null && $scope.FilteredModelIds.length > 0) {
for (var j = $scope.FilteredModelIds.length - 1; j >= 0; j--) {
for (var i = $scope.models.length - 1; i >= 0; i--) {
if ($scope.models[i].ModelId == $scope.FilteredModelIds[j]) {
$scope.FilteredModels.push($scope.models[i]);
}
}
}
}
});
}
Change the model array in the callback.

Categories

Resources