Using ng options in a directive and getting options from an entered service

Create a custom directive containing a select input field.

I use ng-options to populate the selection options, and I'm currently passing data for the parameters using the options attribute associated with the selection area. See below.

 <script> recManagerApp.directive(myDirective, function () { return { restrict: 'E', templateUrl: '/templates/directives/mydirective.html', scope: { mySelectedValue: "=", options : "=" } }; }); </script> <my-directive my-selected-value="usersValue" options="myDataService.availbleOptions"></my-directive> <div> <select data-ng-model="mySelectedValue" data-ng-options="item for item in options"> <option value="">Select something</option> </select> </div> 

The above works as expected, correctly fills in the parameters, selects the correct value and has two-way binding to the property in the parent area.

However, Id rather does not pass parameters using the attribute in the my-directive element and instead enters a service (myDataService), which can provide data for ng options. However, when I try to do this (in different ways), no parameters are created, despite the correct injection of the service and the data available. Can anyone suggest a way to do this?

 recManagerApp.directive(myDirective, function (myDataService) { return { restrict: 'E', templateUrl: '/templates/directives/mydirective.html', scope: { mySelectedValue: "=", options : myDataService.availableOptions } }; }); 

thanks

Mat

+4
source share
1 answer

In my opinion, you have several options (as indicated in the comments):

1. create a controller for the directive

Use the controller in the directive template, i.e.

 <div ng-controller="SelectController"> <!-- your select with the ngOptions --> </div> 

and create a SelectController as a regular controller:

 var app = angular.module("app.controllers", []) app.controller("SelectController", ['$scope', 'myDataService', function(scope, service) { scope.options = service.whatEverYourServiceDoesToProvideThis() }]); 

You can also give your directive a controller that works the same way:

 recManagerApp.directive(myDirective, function () { return { restrict: 'E', templateUrl: '/templates/directives/mydirective.html', scope: { mySelectedValue: "=", }, controller: ['$scope', 'myDataService', function(scope, service) { scope.options = service.whatEverYourServiceDoesToProvideThis() }] }; }); 

2. introducing it into a directive and using it in a link

 recManagerApp.directive(myDirective, function (myDataService) { return { restrict: 'E', templateUrl: '/templates/directives/mydirective.html', scope: { mySelectedValue: "=" }, link: function(scope) { scope.options = myDataService.whatEverYourServiceDoesToProvideThis() } }; }); 
+5
source

Source: https://habr.com/ru/post/1495480/


All Articles