Angular JS - How to update information on ng-repeat from controller? - html

I have a select options and a couple of textareas inside an ng-repeat and what I would like to do is, when I select an option from the menu the respective set of textareas show up some information that belongs to what I just selected.
Instead of doing this all of the textareas created with the ng-repeat show the information.
Here's the link to a JSFiddle that may explain better the problem:
https://jsfiddle.net/711yvm8g/5/
Here's the HTML code:
<div ng-app="App">
<div ng-controller="Ctrl">
<div ng-repeat="data in carData">
<select ng-model = "carSelected" ng-change = "changeInfo(carSelected)" data-ng-options = "car as car.name for car in cars">
<option value = "">Select car</option>
</select>
<textarea>{{colorData}}</textarea>
<textarea>{{yearData}}</textarea>
</div>
And here's the Javascript code:
angular.module('App', []);
function Ctrl($scope) {
//This carData object was created only to make the ng-repeat show multiple instances of the fields.
$scope.carData = {
a:"abc",
b:"def"
}
$scope.cars = [{
name: "Volvo"
}, {
name: "Saab"
}]
var volvoInfo = {
color:"Blue",
year:"2016"
}
var saabInfo = {
color:"Red",
year:"2015"
}
$scope.changeInfo = function(carSelected) {
if(carSelected.name == "Volvo") {
$scope.colorData = volvoInfo.color;
$scope.yearData = volvoInfo.year;
} else {
$scope.colorData = saabInfo.color;
$scope.yearData = saabInfo.year;
}
}
}
Is there a way I can solve this issue? Thanks a lot.

You should restructure your code to use arrays of objects. That way it is easier to manage.
angular.module('App', []);
function Ctrl($scope) {
let carInfoModel = {
name: '',
color: '',
year: '',
}
$scope.cars = [angular.copy(carInfoModel),angular.copy(carInfoModel)]
$scope.carsInfo = [{
name: 'Volvo',
color: 'Blue',
year: "2016"
}, {
name: 'Saab',
color: 'Red',
year: "2015"
}]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="App">
<div ng-controller="Ctrl">
<div ng-repeat="data in cars">
<select ng-model="data" data-ng-options="car as car.name for car in carsInfo">
<option value="">Select car</option>
</select>
<textarea>{{data.color}}</textarea>
<textarea>{{data.year}}</textarea>
</div>
</div>
</div>

Try Ctrl.colorData and Ctrl.yearData for your textarea bindings

Related

Separate values in select containing 2 object

My contains 2 different objects, obj1 and obj2.
<select multiple class="full-width" style="min-height: 200px" ng-model="vm.obj1" >
<optgroup label="First obj">
<option ng-repeat="item in vm.obj1" >{{item.valeur}}</option>
</optgroup>
<optgroup label="Second obj">
<option ng-repeat="item in vm.obj2">{{item.libelle}}</option>
</optgroup>
</select>
obj1 = {[
0: {valeur: non},
1: {valeur: oui}
]}
obj2 = {[
0: {libelle: instance},
]}
What I get when I select values :
What I actually want :
I want the values to be in separated arrays since they are both from different objects so 1 array with ['oui','non'] and the second array with ['instance']. How can I do that ?
Visual of the dropdown ( sorry for the big blue lines I wanted to stay on the point with the datas I made in the question )
You can use ngChange to respond to any changes to the ngModel value and store that in a new property:
function ctrl($scope) {
$scope.options = [{
name: "A",
options: ["A1", "A2"]
},
{
name: "B",
options: ["B1", "B2"]
},
];
$scope.parseSelection = function() {
const selected = {};
// Loop over the selected options and check from which group they came
$scope.rawSelected.forEach((value) => {
$scope.options.forEach(({ name, options }) => {
if (options.includes(value)) {
// The option comes from the current group
if (!selected[name]) {
selected[name] = [];
}
selected[name].push(value);
}
});
});
$scope.selected = selected;
};
}
angular.module("app", [])
.controller("ctrl", ctrl)
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select multiple ng-model="rawSelected" ng-change="parseSelection()">
<optgroup ng-repeat="group in options" label="group.name">
<option ng-repeat="option in group.options">{{option}}</option>
</optgroup>
</select>
{{rawSelected}} - {{selected}}
</div>

How to use ng if condition in a single div for multiple condition

I have a select dropdown,and divs coming from loop.Here when I change the drop down option to city,my div id should change to one,two three which comes from details column from json.Again when I change the drop down option to state,my div id should change to title1,title2 title3 which comes from title column from json.Here it is working fine but I am creating new divs for each condition,can it possible to make in a single div with multiple condition.Here is the code below.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-if="id=='city'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.details}}" >hello</div>
</div>
<div ng-if="id=='state'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.title}}" >hello</div>
</div>
<div ng-if="id=='country'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.name}}" >hello</div>
</div>
script
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [
{
title: 'title1',
name:'name1',
details:'one'
},
{
title: 'title2',
name:'name2',
details:'two'
},
{
title: 'title3',
name:'name2',
details:'three'
}
]
$scope.update = function() {
if($scope.x == 'city'){
$scope.id='city';
}
if($scope.x == 'state'){
$scope.id='state';
}
if($scope.x == 'country'){
$scope.id='country';
}
}
});
To achieve the desired result, try to:
create an attr for each value - city, state and country, like so:
if($scope.x == 'city'){
$scope.id='city';
$scope.attr = 'details';
}
Use {{emp[attr]}} to display values based on the dropdown selection:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [{
title: 'title1',
name: 'name1',
details: 'one'
},
{
title: 'title2',
name: 'name2',
details: 'two'
},
{
title: 'title3',
name: 'name2',
details: 'three'
}
]
$scope.update = function() {
if ($scope.x == 'city') {
$scope.id = 'city';
$scope.attr = 'details';
}
if ($scope.x == 'state') {
$scope.id = 'state';
$scope.attr = 'title';
}
if ($scope.x == 'country') {
$scope.id = 'country';
$scope.attr = 'name';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-repeat="emp in groups" ng-attr-id="{{emp[attr]}}">{{emp[attr]}}</div>
</div>
</div>
codepen - https://codepen.io/nagasai/pen/wRQWRM
To this in a singal element you can use a nested ternary operator. For your case it will look like that:
<div ng-repeat="emp in groups" ng-attr-id="{{id=='city' ? emp.details : id=='state' ? emp.title : emp.name}}" >hello</div>
I didn't implement this on angular 1 but it works on angular 2. Angular built in directive (ngif, ngfor ngclass etc) works almost same for both versions.

How to pre-select radio radio button with Angular JS which is bound to model within ng-repeat

I have the following HTML:
<div ng-controller="CreateSpreadsheetCtrl as csCtrl" ng-init="csCtrl.init()">
<div ng-repeat="x in csCtrl.ProcessingTypeMasters">
<input type="radio" name="proctype"
ng-model="$parent.csCtrl.Template.ProcessingTypeMaster"
ng-value="x" /> {{x.LocalizedName}}
</div>
</div>
Inside the CreateSpreadsheetCtrl.init(), we are loading an array called "ProcessingTypeMasters" (csCtrl.ProcessingTypeMasters) which contains a list of objects (e.g. {Id:1, Name: "Type 1" }, {Id:2, Name: "Type 2" }).
Also in the init() method, we load this "csCtrl.Template" object, which has a property inside it called "ProcessingTypeMaster" (csCtrl.Template.ProcessingTypeMaster).
With the above code, it binds correctly to the model and when you change the selection csCtrl.Template.ProcessingTypeMaster is bound correctly.
However, when csCtrl.Template.ProcessingTypeMaster is pre-loaded with an existing object, it doesn't select it in the UI when the page initially loads.
Any ideas on what we are missing here?
when csCtrl.Template.ProcessingTypeMaster is pre-loaded with an existing object, it doesn't select it in the UI when the page initially loads.
The model value must be a reference to the exact object that appears in the collection - a copy won't work.
Example using an object not in the collection (won't work)
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('CreateSpreadsheetCtrl', [MyCtrl]);
function MyCtrl() {
var vm = this;
vm.ProcessingTypeMasters = [{
id: 0,
LocalizedName: 'Option 0'
}, {
id: 1,
LocalizedName: 'Option 1'
}, {
id: 2,
LocalizedName: 'Option 2'
}];
vm.Template = {
//This is a different object - it doesn't exist in the collection!
ProcessingTypeMaster: {
id: 1,
LocalizedName: 'Option 1'
}
}
}
</script>
<div ng-app="myApp">
<div ng-controller="CreateSpreadsheetCtrl as csCtrl" ng-init="csCtrl.init()">
Model value: {{csCtrl.Template.ProcessingTypeMaster}}
<div ng-repeat="x in csCtrl.ProcessingTypeMasters">
<input type="radio" name="proctype" ng-model="$parent.csCtrl.Template.ProcessingTypeMaster" ng-value="x" />{{x.LocalizedName}}
</div>
</div>
</div>
Example using an object directly from the collection
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script>
var myApp = angular.module('myApp', []);
myApp.controller('CreateSpreadsheetCtrl', [MyCtrl]);
function MyCtrl() {
var vm = this;
vm.ProcessingTypeMasters = [{
id: 0,
LocalizedName: 'Option 0'
}, {
id: 1,
LocalizedName: 'Option 1'
}, {
id: 2,
LocalizedName: 'Option 2'
}];
vm.Template = {
//Now we're using a reference to an object in the collection
ProcessingTypeMaster: vm.ProcessingTypeMasters[1]
}
}
</script>
<div ng-app="myApp">
<div ng-controller="CreateSpreadsheetCtrl as csCtrl" ng-init="csCtrl.init()">
Model value: {{csCtrl.Template.ProcessingTypeMaster}}
<div ng-repeat="x in csCtrl.ProcessingTypeMasters">
<input type="radio" name="proctype" ng-model="$parent.csCtrl.Template.ProcessingTypeMaster" ng-value="x" />{{x.LocalizedName}}
</div>
</div>
</div>

Angular 2: Get Values of Multiple Checked Checkboxes

My problem is really simple: I have a list of checkboxes like this:
<div class="form-group">
<label for="options">Options :</label>
<label *ngFor="#option of options" class="form-control">
<input type="checkbox" name="options" value="option" /> {{option}}
</label>
</div>
And I would like to send an array of the selected options, something like:
[option1, option5, option8] if options 1, 5 and 8 are selected. This array is part of a JSON that I would like to send via an HTTP PUT request.
Thanks for your help!
Here's a simple way using ngModel (final Angular 2)
<!-- my.component.html -->
<div class="form-group">
<label for="options">Options:</label>
<div *ngFor="let option of options">
<label>
<input type="checkbox"
name="options"
value="{{option.value}}"
[(ngModel)]="option.checked"/>
{{option.name}}
</label>
</div>
</div>
// my.component.ts
#Component({ moduleId:module.id, templateUrl:'my.component.html'})
export class MyComponent {
options = [
{name:'OptionA', value:'1', checked:true},
{name:'OptionB', value:'2', checked:false},
{name:'OptionC', value:'3', checked:true}
]
get selectedOptions() { // right now: ['1','3']
return this.options
.filter(opt => opt.checked)
.map(opt => opt.value)
}
}
I have find a solution thanks to Gunter! Here is my whole code if it could help anyone:
<div class="form-group">
<label for="options">Options :</label>
<div *ngFor="#option of options; #i = index">
<label>
<input type="checkbox"
name="options"
value="{{option}}"
[checked]="options.indexOf(option) >= 0"
(change)="updateCheckedOptions(option, $event)"/>
{{option}}
</label>
</div>
</div>
Here are the 3 objects I'm using:
options = ['OptionA', 'OptionB', 'OptionC'];
optionsMap = {
OptionA: false,
OptionB: false,
OptionC: false,
};
optionsChecked = [];
And there are 3 useful methods:
1. To initiate optionsMap:
initOptionsMap() {
for (var x = 0; x<this.order.options.length; x++) {
this.optionsMap[this.options[x]] = true;
}
}
2. to update the optionsMap:
updateCheckedOptions(option, event) {
this.optionsMap[option] = event.target.checked;
}
3. to convert optionsMap into optionsChecked and store it in options before sending the POST request:
updateOptions() {
for(var x in this.optionsMap) {
if(this.optionsMap[x]) {
this.optionsChecked.push(x);
}
}
this.options = this.optionsChecked;
this.optionsChecked = [];
}
create a list like :-
this.xyzlist = [
{
id: 1,
value: 'option1'
},
{
id: 2,
value: 'option2'
}
];
Html :-
<div class="checkbox" *ngFor="let list of xyzlist">
<label>
<input formControlName="interestSectors" type="checkbox" value="{{list.id}}" (change)="onCheckboxChange(list,$event)">{{list.value}}</label>
</div>
then in it's component ts :-
onCheckboxChange(option, event) {
if(event.target.checked) {
this.checkedList.push(option.id);
} else {
for(var i=0 ; i < this.xyzlist.length; i++) {
if(this.checkedList[i] == option.id) {
this.checkedList.splice(i,1);
}
}
}
console.log(this.checkedList);
}
<input type="checkbox" name="options" value="option" (change)="updateChecked(option, $event)" />
export class MyComponent {
checked: boolean[] = [];
updateChecked(option, event) {
this.checked[option]=event; // or `event.target.value` not sure what this event looks like
}
}
I have encountered the same problem and now I have an answer I like more (may be you too). I have bounded each checkbox to an array index.
First I defined an Object like this:
SelectionStatusOfMutants: any = {};
Then the checkboxes are like this:
<input *ngFor="let Mutant of Mutants" type="checkbox"
[(ngModel)]="SelectionStatusOfMutants[Mutant.Id]" [value]="Mutant.Id" />
As you know objects in JS are arrays with arbitrary indices. So the result are being fetched so simple:
Count selected ones like this:
let count = 0;
Object.keys(SelectionStatusOfMutants).forEach((item, index) => {
if (SelectionStatusOfMutants[item])
count++;
});
And similar to that fetch selected ones like this:
let selecteds = Object.keys(SelectionStatusOfMutants).filter((item, index) => {
return SelectionStatusOfMutants[item];
});
You see?! Very simple very beautiful. TG.
Here's a solution without map, 'checked' properties and FormControl.
app.component.html:
<div *ngFor="let item of options">
<input type="checkbox"
(change)="onChange($event.target.checked, item)"
[checked]="checked(item)"
>
{{item}}
</div>
app.component.ts:
options = ["1", "2", "3", "4", "5"]
selected = ["1", "2", "5"]
// check if the item are selected
checked(item){
if(this.selected.indexOf(item) != -1){
return true;
}
}
// when checkbox change, add/remove the item from the array
onChange(checked, item){
if(checked){
this.selected.push(item);
} else {
this.selected.splice(this.selected.indexOf(item), 1)
}
}
DEMO
I hope this would help someone who has the same problem.
templet.html
<form [formGroup] = "myForm" (ngSubmit) = "confirmFlights(myForm.value)">
<ng-template ngFor [ngForOf]="flightList" let-flight let-i="index" >
<input type="checkbox" [value]="flight.id" formControlName="flightid"
(change)="flightids[i]=[$event.target.checked,$event.target.getAttribute('value')]" >
</ng-template>
</form>
component.ts
flightids array will have another arrays like this
[ [ true, 'id_1'], [ false, 'id_2'], [ true, 'id_3']...]
here true means user checked it, false means user checked then unchecked it.
The items that user have never checked will not be inserted to the array.
flightids = [];
confirmFlights(value){
//console.log(this.flightids);
let confirmList = [];
this.flightids.forEach(id => {
if(id[0]) // here, true means that user checked the item
confirmList.push(this.flightList.find(x => x.id === id[1]));
});
//console.log(confirmList);
}
In Angular 2+ to 9 using Typescript
Source Link
we can use an object to bind multiple Checkbox
checkboxesDataList = [
{
id: 'C001',
label: 'Photography',
isChecked: true
},
{
id: 'C002',
label: 'Writing',
isChecked: true
},
{
id: 'C003',
label: 'Painting',
isChecked: true
},
{
id: 'C004',
label: 'Knitting',
isChecked: false
},
{
id: 'C004',
label: 'Dancing',
isChecked: false
},
{
id: 'C005',
label: 'Gardening',
isChecked: true
},
{
id: 'C006',
label: 'Drawing',
isChecked: true
},
{
id: 'C007',
label: 'Gyming',
isChecked: false
},
{
id: 'C008',
label: 'Cooking',
isChecked: true
},
{
id: 'C009',
label: 'Scrapbooking',
isChecked: false
},
{
id: 'C010',
label: 'Origami',
isChecked: false
}
]
In HTML Template use
<ul class="checkbox-items">
<li *ngFor="let item of checkboxesDataList">
<input type="checkbox" [(ngModel)]="item.isChecked" (change)="changeSelection()">{{item.label}}
</li>
</ul>
To get selected checkboxes, add the following method in class
// Selected item
fetchSelectedItems() {
this.selectedItemsList = this.checkboxesDataList.filter((value, index) => {
return value.isChecked
});
}
// IDs of selected item
fetchCheckedIDs() {
this.checkedIDs = []
this.checkboxesDataList.forEach((value, index) => {
if (value.isChecked) {
this.checkedIDs.push(value.id);
}
});
}
I have just simplified little bit for those whose are using list of
value Object.
XYZ.Comonent.html
<div class="form-group">
<label for="options">Options :</label>
<div *ngFor="let option of xyzlist">
<label>
<input type="checkbox"
name="options"
value="{{option.Id}}"
(change)="onClicked(option, $event)"/>
{{option.Id}}-- {{option.checked}}
</label>
</div>
<button type="submit">Submit</button>
</div>
** XYZ.Component.ts**.
create a list -- xyzlist.
assign values, I am passing values from Java in this list.
Values are Int-Id, boolean -checked (Can Pass in Component.ts).
Now to get value in Componenet.ts.
xyzlist;//Just created a list
onClicked(option, event) {
console.log("event " + this.xyzlist.length);
console.log("event checked" + event.target.checked);
console.log("event checked" + event.target.value);
for (var i = 0; i < this.xyzlist.length; i++) {
console.log("test --- " + this.xyzlist[i].Id;
if (this.xyzlist[i].Id == event.target.value) {
this.xyzlist[i].checked = event.target.checked;
}
console.log("after update of checkbox" + this.xyzlist[i].checked);
}
I just faced this issue, and decided to make everything work with as less variables as i can, to keep workspace clean. Here is example of my code
<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />
Method, which called on change is pushing value in model, or removing it.
public changeModel(ev, list, val) {
if (ev.target.checked) {
list.push(val);
} else {
let i = list.indexOf(val);
list.splice(i, 1);
}
}
#ccwasden solution above works for me with a small change, each checkbox must have a unique name otherwise binding wont works
<div class="form-group">
<label for="options">Options:</label>
<div *ngFor="let option of options; let i = index">
<label>
<input type="checkbox"
name="options_{{i}}"
value="{{option.value}}"
[(ngModel)]="option.checked"/>
{{option.name}}
</label>
</div>
</div>
// my.component.ts
#Component({ moduleId:module.id, templateUrl:'my.component.html'})
export class MyComponent {
options = [
{name:'OptionA', value:'1', checked:true},
{name:'OptionB', value:'2', checked:false},
{name:'OptionC', value:'3', checked:true}
]
get selectedOptions() { // right now: ['1','3']
return this.options
.filter(opt => opt.checked)
.map(opt => opt.value)
}
}
and also make sur to import FormsModule in your main module
import { FormsModule } from '#angular/forms';
imports: [
FormsModule
],
Since I spent a long time solving a similar problem, I'm answering to share my experience.
My problem was the same, to know, getting many checkboxes value after a specified event has been triggered.
I tried a lot of solutions but for me the sexiest is using ViewChildren.
import { ViewChildren, QueryList } from '#angular/core';
/** Get handle on cmp tags in the template */
#ViewChildren('cmp') components: QueryList<any>;
ngAfterViewInit(){
// print array of CustomComponent objects
console.log(this.components.toArray());
}
Found here: https://stackoverflow.com/a/40165639/4775727
Potential other solutions for ref, there are a lot of similar topic, none of them purpose this solution...:
Angular 6: How to build a simple multiple checkbox to be checked/unchecked by the user?
Angular 6 How To Get Values From Multiple Checkboxes and Send in From
Angular how to get the multiple checkbox value?
Angular 2: Get Values of Multiple Checked Checkboxes
https://medium.com/#vladguleaev/reusable-angular-create-multiple-checkbox-group-component-84f0e4727677
https://netbasal.com/handling-multiple-checkboxes-in-angular-forms-57eb8e846d21
https://medium.com/#shlomiassaf/the-angular-template-variable-you-are-missing-return-of-the-var-6b573ec9fdc
https://www.bennadel.com/blog/3205-using-form-controls-without-formsmodule-or-ngmodel-in-angular-2-4-1.htm
How to get checkbox value in angular 5 app
Angular 2: Get Values of Multiple Checked Checkboxes
Filter by checkbox in angular 5
How to access multiple checkbox values in Angular 4/5

How to clear a Text Box in angularJS, when click any link in the page AngularJS

I've a search box and multiple categories links available in the HTML page.
as soon as user input in searchBox, i want to show:
p in Products | filter {serachedText}
When user clicks a category hyperlink, i want to show
p in Products | filter {categoryID}
But because serachedText is still avialble, result showing for
p in Products | filter {categoryID} | filter {serachedText}
Is there any way i can clear the serachedText as soon as user clicks on anylink.
That would be really easy to do in angularjs.
In html.
<input ng-model="mytext">
<a href ng-click="mytext=''">Clear Text</a>
jsfiddle is here.
Your filter expression is wrong.
if your data is a JSON array having category and name properties like so:
self.Products = [
{ category: 1, name: 'Pencil' },
{ category: 1, name: 'Notebook' },
{ category: 2, name: 'Kitten' }
];
And you are binding the following things for the selected category and search text:
self.category = 1;
self.searchText = 'pen';
You could create a complex filter expression like so:
filter: { category: vm.category | name: vm.searchText }
This will filter both on category and searchText or in combination.
To clear out the searchText, you can watch if category changes using $scope.$watch and when it changes, clear up the searchText.
Take a look at the example below or at http://plnkr.co/edit/OEDvOn. In the example, my filter expression is a bit more complicated since the selected category is actually an object containing value and name properties for the selected category, thus I need to add .value to get the right thing to pass to the filter.
Another point: For doing client side filtering, this is fine, but if you are filtering on server side, I'd rather get the filtering done on a service layer and just returned the filtered result instead of all possible data... save bandwidth and transfer time.
(function(undefined) {
'use strict';
angular.module('myApp',[]);
angular.module('myApp')
.controller('searchCtrl', searchCtrl);
searchCtrl.$inject = ['$log', '$scope'];
function searchCtrl($log, $scope) {
/* jshint validthis: true */
var self = this;
self.searchText = undefined;
self.categories = [
{ value: undefined, name: 'All' },
{ value: 1, name: 'Fruit' },
{ value: 2, name: 'Snacks' },
{ value: 3, name: 'Flower' },
{ value: 4, name: 'Pet' },
{ value: 5, name: 'Stationary' }
];
self.category = self.categories[0];
self.data = [
{ category: 1, name: 'Apple' },
{ category: 1, name: 'Grapes' },
{ category: 2, name: 'Dorito' },
{ category: 2, name: 'KitKat' },
{ category: 3, name: 'Roses' },
{ category: 3, name: 'Orchid' },
{ category: 4, name: 'Hamster' },
{ category: 4, name: 'Kitten' },
{ category: 5, name: 'Pencil' },
{ category: 5, name: 'Notebook' }
];
$scope.$watch(function() { return self.category; }, function(val, old) {
self.searchText = undefined;
});
}
}());
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div class="container" ng-app="myApp" ng-controller="searchCtrl as vm">
<div class="form-group">
<label>Category</label>
<select class="form-control" ng-options="cat.name for cat in vm.categories" ng-model="vm.category">
</select>
</div>
<div class="input-group">
<input class="form-control" type="textbox" ng-model="vm.searchText" placeholder="Search text here..." />
<span class="input-group-btn">
<button type="button" class="btn btn-primary">
<i class="glyphicon glyphicon-search"></i> Search</button>
</span>
</div>
<div class="well well-sm" style="margin-top:20px">
<ul ng-repeat="item in vm.data | filter:{category:vm.category.value, name:vm.searchText}">
<li>{{item.name}}</li>
</ul>
</div>
</div>
I'd suggest directive will be the best option
MarkUp
<input ng-model="mytext">
<a href ng-click="mytext=''" clear="mytext">Clear Text</a>
Directive
app.directive('a', function() {
return {
restrict: 'E',
scope: {
clear: '='
},
compile: function(scope, ele, attrs) {
ele.on('click', function() {
scope.$apply(function() {
scope.clear = undefined;
})
})
}
}
})