Reputation: 12972
I need your help about an AngularJS issue: I'm creating a Directive to manage a customer/offices situation (two select boxes, one for customers and one for offices related to the customer selected). When I load the html page containing the directive I must check if an officeID "is present" and, in that case, fill the html selects with the right values based on that officeID. To do so I must call a function in the controller of the directive. This is my directive:
angular.module("app").directive('myCustomersOffices', ["ConstantsService",
function(ConstantsService){
return {
restrict: 'E',
scope : {
office : '='
},
controller : 'customersOfficesController',
templateUrl: ConstantsService.URL.BASE_APP+'/bundles/customers/views/customersOffices.html',
link : function (scope, elem, attrs, controller) {
//!!!!!!!!!!!!
//Here I would like to call getOfficesByOfficeID(officeID), a function
//contained in the controller
//!!!!!!!!!!!!!!!!!!!!
}
};
}]);
This is my html directive template:
<div id="customer-and-offices">
<select class="form-control" id="activity-customers"
data-ng-change="getOffices(selectedCustomer)" data-ng-options="customer.ID as customer.name for customer in customers" data-ng-model="selectedCustomer">
<option value="">Choose customer...</option>
</select>
<select class="form-control" id="activity-offices"
data-ng-options="office.ID as office.name for office in customerOffices" data-ng-model="office">
<option value="">Choose office...</option>
</select>
</div>
and this is the way I call the directive in the main html page:
<my-customers-offices office="activity.get().officeID"></my-customers-offices>
All the stuff that you can read above works properly to retrieve the office starting from the customer selection (the "normal" case). But, as I said, I would like to call a function getOfficeByOffice if an officeID "is present" when the html main page "is ready". How can I pass the possible officeID to the link directive function? Thank you in advance.
Upvotes: 0
Views: 106
Reputation: 2996
Usually, it's a bad idea to have methods in your controllers. I'd advise that you create service modules that contain functions that can be shared across directives and controllers. Then its only a matter of injecting the the module (and the service) anywhere in your main application.
Here's a working fiddle that is somewhat close to what you want.
The code:
'use strict';
var module = angular.module("myApp", [])
.controller('MyCtrl', function ($scope) {
$scope.variable = "this";
})
.directive('myDirective', function () {
return {
template: '{{variable}} is accessible here, so are functions.'
};
});
And the HTML;
<div ng-app="myApp" ng-controller="MyCtrl">
<div my-directive></div>
</div>
Upvotes: 1