Reputation: 201
I am learning Angular JS and trying to create a dropdown box as a directive. I have done this simply (in my actual code I use a templateURL) but now I need to be able to read the attribute 'value' from the dropdown box and respond to the changes.
I can do this in Jquery and have written a small scrip to show the behaviour that I want to see. My question is how to replicate this behaviour just using Angular.
Here is the test script in Plunker: http://plnkr.co/edit/Vguftwf8zfY7ZeAoGYfq
It is also below:
<!DOCTYPE html>
<html ng-app="test">
<head>
<title>This is a test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="dd"><runs></runs></div>
<div id="other">Here is other input box
<input type='text' name='other'/></div>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.4/angular.min.js"> </script>
<script>
'use strict'
var app = angular.module('test', [])
app.directive('runs', function() {
return{
restrict: 'E',
template: '<select name="runs" id="runs"><option value ="0">Zero</option><option value ="1">One</option><option value ="2">Two</option><option value ="other">Other</option></select>',
scope: {
value: '@'
},
link: function(scope, element, attrs) {
//if (attrs('value') === 'other'){
// set other div to visible
// }
}
}
})
$(document).ready(function(){
$("#other").hide();
$("#runs").change(function(){
if($("#runs option:selected").val()==="other"){
$("#other").show();
} else{
$("#other").hide();
}
})
})
</script>
</body>
Upvotes: 1
Views: 1236
Reputation: 31
Here is a directive example, hope this will help you.
<kaze-dropdown is-button ng-model="item" items="options" callback="callbackFunc(item)"></kaze-dropdown>
Upvotes: 0
Reputation: 171679
First you want the <select>
to be bound to a data model using ng-model
.
When angular encounters ng-model
in the html, if the scope that it is encountered within doesn't contain this variable, angular creates it.
<select ng-model="model.runs">
I arbitrarily named the object model
and the property runs
.
Now you can use ng-show
to evaluate that value :
<div id="other" ng-show="model.runs=='other'">
Many of angular's built in directives will evaluate javascript expressions. In this case will evaluate model.runs=='other'
as a boolean.
Note that changing the select will now toggle the display of an element without any additional script having been written, just a little bit of markup modification
Upvotes: 1