Angularjs Angular ng click不在自定义指令内执行函数
我已经创建了一个自定义指令,并在状态hamburgerClick上添加了一个控制器和一个函数。以下是我的代码:Angularjs Angular ng click不在自定义指令内执行函数,angularjs,angularjs-directive,Angularjs,Angularjs Directive,我已经创建了一个自定义指令,并在状态hamburgerClick上添加了一个控制器和一个函数。以下是我的代码: directivesModule.directive('headerDir', [function () { var headerDir = { restrict: 'E', templateUrl: 'App/scripts/main/directives/header/HeaderDir.html', replace: tr
directivesModule.directive('headerDir', [function () {
var headerDir = {
restrict: 'E',
templateUrl: 'App/scripts/main/directives/header/HeaderDir.html',
replace: true
};
headerDir.controller = ['$state', function ($state) {
$state.hamburgerClick = function() {
var app = $('.application-wrap');
if (app.hasClass('menu-opened')) {
app.removeClass('menu-opened');
}
else {
app.addClass('menu-opened');
}
};
}];
return headerDir;
}]);
<div>
<span class="menu-overlay"></span>
<section class="menu-bar">
<article>
<div class="menu-button" ng-click="hamburgerClick()">
<span class="hamburger-icon"></span>
</div>
<h1 class="logo"></h1>
</article>
</section>
directivesModule.directive('headerDir',[function(){
var headerDir={
限制:'E',
templateUrl:'App/scripts/main/directions/header/HeaderDir.html',
替换:正确
};
headerDir.controller=['$state',函数($state){
$state.hamburgerClick=function(){
var app=$('.application wrap');
if(应用程序hasClass(“菜单打开”){
应用程序removeClass(“菜单打开”);
}
否则{
app.addClass(“菜单打开”);
}
};
}];
返回磁头;
}]);
我的问题是,由于某种原因,当我尝试单击函数时,该函数无法执行。有人知道我做错了什么吗?您的代码中有几点值得怀疑 1) 您应该将$state替换为$scope 2) 在HTML代码中不使用指令。而是引用名为“article”的指令 3) 使用replace:true,它将替换指令的原始内容。除非您计划将$('.menu button')定义为header dir指令,否则对hamburgerClick的调用将被删除 此外,您还可以替换
var app = $('.application-wrap');
if (app.hasClass('menu-opened')) {
app.removeClass('menu-opened');
}
else {
app.addClass('menu-opened');
}
与
试试这个
directivesModule.directive('headerDir', [function () {
return{
restrict: 'E',
templateUrl: 'App/scripts/main/directives/header/HeaderDir.html',
replace: true
controller: function($scope){
$scope.hamburgerClick = function() {
var app = $('.application-wrap');
$('.application-wrap').toggleClass('menu-opened');
};
}
}
}]);
尝试使用$scope而不是$state1)将$scope而不是$state注入指令控制器。2)指令甚至没有包含您发布的din标记。
directivesModule.directive('headerDir', [function () {
return{
restrict: 'E',
templateUrl: 'App/scripts/main/directives/header/HeaderDir.html',
replace: true
controller: function($scope){
$scope.hamburgerClick = function() {
var app = $('.application-wrap');
$('.application-wrap').toggleClass('menu-opened');
};
}
}
}]);