Reputation: 717
I have some troubles while trying to update the current selected value of an option in ng-options.
I have an array which contains one object. The object has 'value' and 'name' properties whose values are constant.
I am using this constant array in a custom directive with select and ng-options. This is part of the directive's html:
<select
name="{{vm.name}}"
ng-model="vm.model"
ng-options="arrayObject.value as arrayObject.name for arrayObject in
vm.constantArrayofObject">
</select>
And I use this directive in a form of a view.
<directive
model=""
form="someForm"
name="someName">
</directive>
In the controller's view I have a object 'controllerObject' which has an array of objects as a property, like this:
controllerObject.properties: [
{
value: "someValue",
name: "someName"
}
]
I have to bind the value and the name of selected option to the value and the name of the object in the controllerObject.properties array and to pass them to update() function. But I am not sure how to access the controller object in the directive in the html view. Because it already displays the values of the object in the constant array. That's why I did not put anything in model property of the directive. How to connect the two arrays of objects and map the selected value to the value of the object in the controller (and name)?
Any help would be greatly appreciated.
Upvotes: 2
Views: 881
Reputation: 3513
Share the data of options array using isolated scope twwo way data binding "=" operator. For that just have one more attribute select-options with controllerObject.properties array. And then have it inside scope block of directive. So directive to be used can be:
<mydirective field="fielddata" select-options="controllerObject.properties"></mydirective>
DDO:
app.directive('mydirective', function() {
return {
restrict: 'E',
templateUrl: 'dirtemplate.html',
scope: {
field: "=",
selectOptions: "="
},
link: function(scope, element, attrs) {
}
};
});
where dirtemplate.html is :
<select
name="{{field.name}}"
ng-model="field.model"
ng-options="arrayObject.value as arrayObject.name for arrayObject in selectOptions">
</select>
And in views controller define fielddata & controllerObject as :
app.controller('MainCtrl', function($scope) {
$scope.fielddata = {
name: "country",
form: "someForm",
model: ""
};
$scope.controllerObject = {};
$scope.controllerObject.properties = [
{
value: "someValue",
name: "someName"
},
{
value: "Value1",
name: "Name1"
},
{
value: "Value2",
name: "Name2"
}
];
});
Upvotes: 1