-
Notifications
You must be signed in to change notification settings - Fork 27.4k
Extending select directive #13283
Comments
You should set the scope, not the select. Programatic change should always be driven from the scope. I'd say http://stackoverflow.com/a/33618387/787333 is the way to go. |
It's not the way for me. I need use this logic in lots of places so I'd rather have one directive than lots of controllers with duplicates. |
I don't see why you'd have lots of controllers and duplicates. The logic of setting on the scope from a directive would be the same in all places. |
If I'll do your way then for every promise.then(function(items) {
$scope.items = items;
$scope.selectedItem = (items.length === 1) ? items[0] : null;
}) This is ugly Instead I want just to write this: promise.then(function(items) {
$scope.items = items;
}) and be sure that I'll have preselected value if there is only one item in array. |
I still don't see why you can't just assign the scope value in our directive, similar to the example directive you posted. |
Are you are talking about something like this? ngModel.$setViewValue(items[0]); because I can't hardcode scope variable names inside directive. If so then I still have my question - how can I get array of items inside custom directive extending angular's Also I've written a hack inside of scope.$evalAsync(function() { ... }) to be sure that all items were already rendered on the DOM. This is because I can't extend ngOptions which is terminal so I need to write my own bicycle. In a perfect world I would rather write directive like this: angular.module('app')
.directive('selectFirstIfOnlyOne', function() {
return {
require: ['ngModel', 'ngOptions'],
link: function(scope, elem, attrs, ctrls) {
scope.$watch(ctrls[1].options, function(values)) {
if (angular.isDefined(values) && values.length === 1) {
ctrls[0].$setViewValue(values[0]);
}
});
}
};
}); |
Oh, I was focusing on a different aspect of your directive (that you shouldn't use setViewValue). I see how exposing the options could be useful in that case. There's another issue where that has been proposed.#7417 If you want to open a PR which implements this change, I'll be happy to look at it, |
I want to write directive that will check for available options in the scope and preselect some option if only one item present inside ngOptions.
For now I wrote something like this:
and my directive:
And it works. But I want not to pass array values to directive directly but to take them from ngModel or ngOptions.
I found that
SelectController
doesn't provide methods to get all values from<select>
, same forNgModelController
.Same question on StackOverflow.
The text was updated successfully, but these errors were encountered: