如何在指令中调用父作用域函数

时间:2015-11-08 19:37:28

标签: javascript angularjs angularjs-directive

我想在指令模板中调用Controller函数。 这不起作用:

控制器:

myApp.controller('StartController', ['$scope', '$location',  function ($scope, $location) {

    $scope.changeLocation = function (path) {
        $location.path(path);
    }
 }]);

index.html:

<div start-directive changelocation="changeLocation">
</div>

指令:

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);
            });

        }
    };
});

和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>

我做错了什么?

事先提前

1 个答案:

答案 0 :(得分:1)

您尚未使用范围编译元素,您只创建了该模板的编译函数,如$compile(template),它不会编译该元素。您需要通过在其中传递scope参数来调用compile函数。

由于您的指令使用的是可共享范围,因此在调用方法之前无需提及$parent

<强>指令

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
      });

    }
  };
});