AngularJS Example:
HTML
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<p>fooId is currently : {{fooId}}</p>
<app-drop-down model="fooId" options="fooOptions" opt-value="id" opt-label="label" on-change="dropDownChanged"></app-drop-down>
</div>
</div>
JavaScript
var app = angular.module('myApp', []);
app.controller('MainCtrl', function ($scope, $log) {
$scope.fooId = -1;
$scope.fooOptions = [{
id: 1,
label: "A"
}, {
id: 2,
label: "B"
}];
$scope.dropDownChanged = function () {
$log.info('changed : ' + $scope.fooId);
};
});
app.directive('appDropDown', function () {
return {
restrict: 'E',
replace: true,
scope: {
model: '=',
options: '=',
onChange: '='
},
template:
'<div><select ng-model="model" ng-options="a[optValue] as a[optLabel] for a in options"></select></div>',
link: function (scope, element, attrs) {
scope.optValue = attrs.optValue;
scope.optLabel = attrs.optLabel;
scope.$watch('model', function(newValue, oldValue)
{
// Execute function on change
if (scope.onChange !== undefined &&
newValue !== undefined && oldValue !== undefined)
{
scope.onChange();
}
});
}
};
});