List of dynamic checkbox in Angular and JSON API - json

I'm having trouble rendering dynamic checkboxes with JSON API response.
This 2 ng-repeats:
Bringing the listing of categories in BD, and;
ng-model with the selected category listing.
Below my HTML code;
<ul class="list-group">
<li class="list-group-item" ng-repeat="cats in categorias">
<div class="checkbox"><label><input type="checkbox" ng-model="checkbox[item.cats]"><span class="checkbox-material"><span class="check"></span></span></label> {{cats.name}}</div>
</li>
</ul>
JSON/API response (1)
[
{"id":"1","id_module":"1","name":"Esportes"},
{"id":"2","id_module":"1","name":"Entretenimento"},
{"id":"3","id_module":"1","name":"Terror"},
{"id":"4","id_module":"1","name":"Drama"}
]
JSON response (2)
{cats":["1","2"]}
I would like that the checkbox stay checked with the response.
Does anyone have any idea?

Here you have working fiddle, check it
jsfiddle.net/b895j3ay
var app = angular.module("Application", [])
app.controller('Ctrl', function($scope) {
$scope.roles = [{
id: 1,
text: 'guest'
}, {
id: 2,
text: 'user'
}, {
id: 3,
text: 'customer'
}, {
id: 4,
text: 'admin'
}];
$scope.isChecked = function(id, matches) {
var isChecked = false;
angular.forEach(matches, function(match) {
if (match === id) {
isChecked = true;
}
});
return isChecked;
}
$scope.user = {
roles: [2, 4, 3]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.21/angular.min.js"></script>
<div ng-app="Application">
<div ng-controller="Ctrl">
<label ng-repeat="role in roles">
<input type="checkbox" ng-model="user.roles" checklist-value="role.id" ng-checked="isChecked(role.id,user.roles)">{{role.text}}
</label>
</div>
</div>
</div>

Related

[Vue warn]: Property "______" was accessed during render but is not defined on instance

I am currently teaching myself Vue to create a Contact form for a 'mock up' website in order to teach myself user inputs. However I keep getting the same error for multiple cases
//--------------- FORM TITLES ---------------
// Vue object: Titles
const ContactTitles = {
data() {
return {
main_title: 'Contact Us',
name: 'Name',
email_address: 'Email Address',
select_option: 'What is your enquiry about?',
checkboxes: 'Please click on each wrestling company you know:'
}
}
}
Vue.createApp(ContactTitles).mount('#contact-titles')
//--------------- FORM INPUTS ---------------
// Vue object: Inputs
var UserInputs = {
data() {
return {
inputtedName: '',
inputted_email: '',
inputtedMessage: ''
}
},
methods: {
checkInput: function () {
if (this.inputtedName === '' || this.inputtedEmail === '' || this.inputtedMessage === '')
{
alert("Please input in all the fields");
}
}
}
}
Vue.createApp(UserInputs).mount('#contact-form-inputs')
// Vue instance: Select options
Vue.createApp({
data() {
return {
selected: 'None',
options: [
{ text: 'Booking enquiry', value: 'Booking' },
{ text: 'Website improvement', value: 'Website' },
{ text: 'Item enquiry', value: 'Item' },
{ text: 'Previous experiences', value: 'Experience' },
{ text: 'Career opportunity', value: 'Career' }
]
}
}
}).mount('#select-list')
<div class="form_container" id = "contact-titles">
<div class = "form_inputs" id = "contact-form-inputs">
<!--Name input-->
<div class="input_container">
<label for="nameInput">{{name}}</label> <br>
<input id="nameInput" type="text" v-model="inputtedName" placeholder="Enter name">
</div>
<br>
<!--Email input-->
<div class="input_container">
<label for="emailInput">{{email_address}}</label> <br>
<input id="emailInput" type="text" v-model="inputtedEmail" placeholder="example#gmail.com">
</div>
<br>
<!--Selection list-->
<div class="select_container" id = "select-list">
<select v-model="selected">
<label for = "list">{{select_option}}</label> <br>
<option id = "list" v-for="option in options" v-bind:value="option.value">{{option.text}}</option>
</select>
</div>
</div>
</div>
It has the error for inputtedName, inputtedEmail, options and selected, as it states that:
"[Vue warn]: Property "______" was accessed during render but is not defined on instance"
Hopefully another pair of eyes can help me figure out why it is saying these elements are not defined, thanks

How to get list of checkboxes to behave like a dropdown with AngularJS

Dropdowns are fine to get a radio button behaviour and hide a long list... But I never liked them.. They require the user to click in order to see the list and their style don't match the page.
I would like to find a more dynamic way using angular.
How do I display a list of checkboxes and hide all unchecked checkboxes once a checkbox is checked? Unchecking the checkbox should then display all checkboxes again...
I tried the following, but without any luck.
<ul>
<li ng-repeat="album in albums | filter: '{{selected}}' ">
<input type="checkbox" ng-model="selected" ng-value="{{album.name}}" />
</li>
</ul>
If I understand your question well, it should work:
(function() {
"use strict";
angular.module('app', [])
.controller('mainCtrl', function($scope) {
var vm = this;
vm.albums = [
{
"id":"1",
"name":"Album 1"
},
{
"id":"2",
"name":"Album 2"
},
{
"id":"3",
"name":"Album 3"
}
];
vm.selected = {};
vm.disable = {};
$scope.$watch(function() {
return vm.selected;
},
function(newVal, oldVal) {
var newValIndex = 0;
for (var key in newVal) {
if (newVal[key]) {
newValIndex = parseInt(key);
}
}
for (var i = 0; i < vm.albums.length; i++) {
vm.disable[i] = i === newValIndex ? false : newVal[newValIndex.toString()];
}
}, true);
});
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="mainCtrl as main">
<ul>
<li ng-repeat="album in main.albums">
<input type="checkbox" id="album{{$index}}" value="{{album}}" ng-model="main.selected[$index]" ng-disabled="main.disable[$index]">
<label for="album{{$index}}" ng-bind="album.name"></label>
</li>
</ul>
<pre ng-bind="main.selected | json"></pre>
</body>
</html>
I hope it helps.
I found a solution using the controller.
Controller
albums = [
{
"id":"1",
"name":"Album 1"
},
{
"id":"2",
"name":"Album 2"
},
{
"id":"3",
"name":"Album 3"
}
];
$scope.display = ( new Array(albums.lenght) ).fill( true );
var onlyOneTrue = function(){
if ( $filter("filter")( $scope.display , true).length == 1 ){
return true;
} else {
return false;
}
}
$scope.changed = function(index) {
if ( onlyOneTrue() ) {
$scope.display.fill( true );
} else {
$scope.display.fill(false)[index] = true;
}
}
HTML
<ul>
<li ng-repeat="album in albums' ">
<input type="checkbox" ng-show="display[$index]" ng-click="changed($index)">
{{album.name}}
</input>
</li>
</ul>

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

"[object object]" shown when double-clicking input

Below is the template I am using for the directive. In code we are
fetching the data from a service in that data we have all the
information of that particular person. And from that data we are
showing only first name, last name and designtion or company
affiliation.
<div ng-if="model" class="entry-added">
<span class="form-control"><b>{{model.fullName}}</b>, <br/><span class="small-font">{{(model.designation)?model.designation:model.companyAffiliation}}</span></span>
<a ng-click="removePerson()" class="action-remove"><i class="fa fa-remove"></i></a>
</div>
<div ng-show="!model" class="input-group">
<input type="text"
class="form-control"
name="{{name}}"
id="{{name}}"
placeholder="{{placeholder}}"
ng-required="{{isRequired}}"
typeahead-on-select = "change($item, $model, $label)"
ng-model="model"
typeahead-min-length="3",
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
typeahead-template-url="typeAheadTemplate.html"
typeahead-loading="searching"
typeahead-editable="false">
<script type="text/ng-template" id="typeAheadTemplate.html">
<a class="ui-corner-all dropdown" tabindex="-1">
<div class="col-md-2"><img class="dropdown-image" ng-src="https://people.***.com/Photos?empno={{match.model.employeeNumber}}"></div>
<div>
<div bind-html-unsafe="match.model.fullName"></div>
<div bind-html-unsafe="match.model.designation"></div>
</div>
</a>
</script>
I am using a custom directive to display a search field. The drop down is displaying [object object].
Directive
// In backend taxDeptContact is a Person type object
/*
Directive code
*/
(function () {
'use strict';
angular.module('treasuryApp.directives').directive('employeeSearch', employeeSearch);
employeeSearch.$inject = ['$resource', '$rootScope', 'ErrorHandler'];
function employeeSearch($resource, $rootScope, ErrorHandler) {
return {
restrict: 'E',
require: '^form',
scope: {
model: "=",
isRequired: '#',
submitted: "=",
onSelect: '&',
name: '#',
index:'#'
},
link: function(scope, el, attrs, formCtrl) {
//set required attribute for dynamically changing validations
scope.searchEmployees = function (searchTerm) {
var users = [];
var myResult = [];
var result = $resource($rootScope.REST_URL + "/user/getEmployees", {term: searchTerm}).query().$promise.then(function (value) {
//console.log(value)
$.each(value, function(i, o) {
users.push(o);
});
return users;
});
return result;
}
scope.removePerson = function() {
scope.model=null;
}
scope.userNotSelectedFromTypeahead = function(name) {
if(undefined === formCtrl[name]) {
return false;
}
return formCtrl[name].$error.editable;
};
scope.change = function(item, model, label) {
scope.model = item
scope.onSelect(
{name: scope.name, person: scope.model});
},
templateUrl: 'app/components/common/directives/employee-search.tpl.html'
};
}
})();
View that is using the directive
<div class="form-group">
<label class="col-sm-3>Tax Dept Contact</label>
<div class="col-sm-4">
<employee-search model="reqCtrl.requestObj.taxDepartmentContact" name="taxDeptContact" is-required="false" submitted="reqCtrl.submitted"/>
</div>
</div>
Image of the error occuring
Looks like this may be your trouble spot
typeahead="suggestion for suggestion in searchEmployees($viewValue)"
suggestion for suggestion is pulling the whole object. Have you tried displaying a particular attribute of suggestion?
For example: if you had a suggestion.name attribute you would write:
typeahead="suggestion.name for suggestion in searchEmployees($viewValue)"
Finally got the answer: I used autocomplete="off" in my directive and thats all
<input type="text" autocomplete="off" />

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;
})
})
}
}
})