Reputation: 91
I want to call a Controller function in the directive template. This is not working:
Controller:
myApp.controller('StartController', ['$scope', '$location', function ($scope, $location) {
$scope.changeLocation = function (path) {
$location.path(path);
}
}]);
the index.html:
<div start-directive changelocation="changeLocation">
</div>
the directive:
myApp.directive('startDirective', function ($templateRequest, $compile) {
return {
restrict: 'AE',
transclude: true,
link: function (scope, element, attrs) {
var baseSiteUrlPath = $("base").first().attr("href");
$templateRequest(baseSiteUrlPath + '/App/Templates/uxStart.html').then(function (html){
var template = angular.element(html);
element.append(template);
$compile(template);
});
}
};
});
and the uxStart.html
<div class="box1 square1">
<button class="indexBtn" ng-click="$parent.changeLocation('/index')">Fahrplan & Buchung</button>
</div>
<div class="box2 square2">
<button class="serviceBtn" ng-click="changeLocation('/pageNotFound')">Services</button>
</div>
What I am doing wrong?
thx in advance
Upvotes: 0
Views: 292
Reputation: 136184
You have not compiled your element with scope, you have only create the compile function of that template like $compile(template)
, which wouldn't compile that element. You need to call compile function by passing scope parameter in it.
As your directive is using shareable scope, then you don't need to mention $parent
before calling method.
Directive
myApp.directive('startDirective', function($templateRequest, $compile) {
return {
restrict: 'AE',
transclude: true,
link: function(scope, element, attrs) {
var baseSiteUrlPath = $("base").first().attr("href");
$templateRequest(baseSiteUrlPath + '/App/Templates/uxStart.html').then(function(html) {
var template = angular.element(html);
element.append(template);
var linkFn = $compile(template);
//compile it with scope to generated compiled DOM with scope
linkFn(scope); //linking scope with template
});
}
};
});
Upvotes: 1