在Angular中的指令内调用函数

时间:2014-11-06 23:02:44

标签: angularjs angularjs-directive angularjs-ng-click

抱歉,如果之前有人问过这个问题,但我的问题有所不同,希望有人能帮助我。

1)我有一个有很多按钮的指令。我想在这个按钮和指令内部调用一个函数。但我不知道如何。

// Directive for the login header to avoid the duplication of the code
angular.module('App').directive('mainHeader',function(){
    return{
        restrict: 'AE',
        template:'<h1 class="logo"> My App  </h1>'+
        '<button class="btn btn-primary">New User</button>'+
        '<button class="btn btn-primary">New Product</button>'+

            '<span class="dropdown" on-toggle="toggled(open)">'+
                '<a href class="dropdown-toggle">'+
                '<img class="userProfile" src="" alt="User Profile">'+
                '<b class="caret"></b>'+
               '</a>'+
                    // Here on my profile ????
                '<ul class="dropdown-menu pull-right">'+
                    '<li> My Profile </a> </li>'+
                    '<li class="divider"></li>'+
                       // Here on my logout ?????? 
                       // This does not work
                    '<li> <a href="" ng-click="logOut()"> Sign Out </li>'+
                '</ul>'+
            '</span>'
    }
});

我的控制器

(function() {
    var logOutController = function($scope){
      $scope.logOut = function(){
           // Want to call this
        }
    logOutController .$inject = ['$scope'];
    angular.module('App').controller('logOutController ',logOutController );
}());

我的观点只有一行

<div main-header></div>

我不知道该怎么做

更新1: -

请看看Plunker http://plnkr.co/edit/YONVyVvNm4pQGFMU6SkG?p=preview

1 个答案:

答案 0 :(得分:1)

您只需要在您的指令中添加隔离范围:

// Directive for the login header to avoid the duplication of the code
angular.module('App').directive('mainHeader', function () {
    return {
        restrict: 'AE',
        template: '<h1 class="logo"> My App  </h1>' +
        '<button class="btn btn-primary">New User</button>' +
        '<button class="btn btn-primary">New Product</button>' +

        '<span class="dropdown" on-toggle="toggled(open)">' +
        '<a href class="dropdown-toggle">' +
        '<img class="userProfile" src="" alt="User Profile">' +
        '<b class="caret"></b>' +
        '</a>' +
            // Here on my profile ????
        '<ul class="dropdown-menu pull-right">' +
        '<li> My Profile </a> </li>' +
        '<li class="divider"></li>' +
            // Here on my logout ?????? 
            // This does not work
        '<li> <a href="" ng-click="logOut()"> Sign Out </li>' +
        '</ul>' +
        '</span>',
        scope: {
            'logOut': '&onLogOut' //<- this ties your directive's logOut function to an attr on the HTML tag
        }
    }
});

然后您只需将HTML修改为:

<div main-header on-log-out="logOut()"></div>

Plunker Example