i want to use "ng-options" in a directive. First let me show you some code :
fooController.js
init();
function init () {
$scope.randomOptions = [{id: '1', name: 'AAA'},
{id: '2', name: 'BBB'},
{id: '3', name: 'CCC'},
{id: '4', name: 'DDD'},
{id: '5', name: 'EEE'}];
}
index.html
<div sort-container ng-model="fooBy" opts="randomOptions"></div>
foobarDirective.js
foobarDirective = function() {
return {
restrict: 'A',
templateUrl: '/templates/directives/foobarDirective.html',
transclude: true,
scope: {
opts : '='
}
};
};
foobarDirective.html
<select ng-options="item.id as item.name for item in opts"></select>
<div ng-repeat="item in opts track by $index">
%(item.id)% - %(item.name)%
</div>
So that's what I got so far. But ng-options is still not working, besides that I got some questions which might help me to understand directives further.
a) First I tried to deliver the object [$scope.randomOptions] via the opts-attribute in the DIV tag, but that didn't work. I would really prefer not to write an object into the parent.scope at all and just to paste it as option.
b) When I use
opts : '@'
instead of
opts : '='
I can remove the unneeded two-way-binding, but my object won't delivered in the right way. Does '@' also define my object as a string ?
Thanks for helping me out guys :)
ng-options
only works with an accompanying ng-model
(I assume the ng-repeat
works?)
<select ng-model="selectedItem"
ng-options="item.id as item.name for item in opts">
Two-way binding would indeed be a waste (unless you are planning to modify the options from within the directive). "@"
is a one-way string binding.
One way you could create a one-way binding is to use "&"
- this will create a function a result of which is the result of a bound expression. So, while it is somewhat unintuitive way to use "&"
this will give you a one-way bound property:
<foobar opts="randomOptions"></foobar>
Then, inside the directive you would use like so:
<select ng-model="selectedItem"
ng-options="item.id as item.name for item in opts()">
(notice the function at the end opts()
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.