Angular -js: ng-repeat on select element with attribute directive
I have a directive for an element called on-change. The idea is when the selected value changes, it is stored in the variable scope and then another item is selected.
My problem is that items from static are the above, but if I use ng-repeat the onchange stops working.
<select on-change="myvar" ng-repeat="(key, value) in dataset">
<option value="{{key}}">{{value.name}}</option>
</select>
here's my onchange directive:
.directive('onChange', function() {
return {
restrict: 'A',
scope:{'onChange':'=' },
link: function(scope, elm, attrs) {
scope.$watch('onChange', function(nVal) { elm.val(nVal); });
elm.bind('blur', function() {
var currentValue = elm.val();
if( scope.onChange !== currentValue ) {
scope.$apply(function() {
scope.onChange = currentValue;
});
}
});
}
};
})
Any idea on how I can solve this problem?
thank
source to share
What you can do is use ng-model
and $watch
to catch any changes. To reuse it, you can slightly modify your code to $watch
ngModel
.
(I'm just assuming you wanted to do one select
with multiple options, not multiple select
with one option, so I'll change that accordingly)
<select ng-model="myvar" on-change>
<option ng-repeat="(key, value) in dataset" value="{{key}}">{{value.name}}</option>
</select>
New link feature:
link: function(scope, elm, attrs) {
scope.$watch(attrs.ngModel, function (newVal, oldVal) {
if(newVal !== oldVal) {
//Change happened, react accordingly
}
});
}
See my similar answer here
source to share
I suggest you use ngOptions . In your case, it should look something like this:
<select ng-model="myVar" ng-options="key as value.name for (key, value) in dataset"></select>
And, as some people have suggested before me, use $watch
to monitor changes in the model.
$scope.$watch('myVar', function(newValue, oldValue) {
//whatever
});
See a simple example here .
source to share