你好,我有一个汉堡包菜单以下指令:自定义指令在角
angular.module('app.directives')
.directive('hamburger', hamburger);
// Injecting Dependencies
hamburger.$inject = ['$rootScope', '$timeout'];
// Directive's Function, Where All Code is Declared and Executed
function hamburger($rootScope, $timeout) {
return {
restrict: 'E',
scope: {
open: '='
},
templateUrl: 'tpls/directives/hamburger.html',
link: function (scope, elem, attr, ctrl) {
scope.$watch('open', function(newValue, oldValue) {
if (newValue == true) {
$timeout(function() {
elem.addClass("open");
}, 2000);
console.log("This is true");
}
else {
$timeout(function() {
elem.removeClass("open");
}, 2000);
console.log("This is false");
}
});
}
}
}
这是模板:
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
这是我如何使用它在我的观点:
<hamburger class="menu-btn2 pull-left" snap-toggle="left" open="vm.toggleMenu" ng-click="toggle()" ng-dblclick="doNothing()"></hamburger>
现在我在我的视图中有一个函数,它可以在点击时向元素添加一个类。这会打开一个侧面菜单。
现在当我的菜单打开时,我想通过添加一个“打开”类来更改我的菜单图标。
在我的指令中,我有一个名为“open”的属性,它绑定到我的控制器和我的指令。在我的指令链接函数我有一个手表,应该观察变量绑定到“打开”的值,当它变为真时它应该是一个类“打开”的元素,当它变成“假”它应该从元素中移除“open”类。
我已经尝试了一切至今,但似乎无法得到这个工作。在我的终端中没有显示错误,我尝试在我的$ watch中执行console.log()
以查看它是否实际检测到值发生了更改,但那也不起作用,我的控制台中没有记录任何内容。
这是我的切换功能:
vm.toggleMenu = false;
vm.toggle = function() {
vm.toggleMenu = !vm.toggleMenu;
};
这很可能是您使用了错误的绑定类型,“@”绑定是针对字符串的。你可能想用'='做一个双向绑定。阅读更多:https://blog.umur.io/2013/07/02/angularjs-directives-using-isolated-scope-with-attributes/ –
是的,我已经知道了。实际上,当它不起作用时,我实际上使用了“=”我将其更改为“@”。 – user3718908
这段代码看起来不错,你有控制器的代码是否附加到' '? –
CShark