我是 AngularJS 的新手,有一个非常简单的示例,但无法正常工作。我希望有人能告诉我我错过了什么。它应该改变鼠标输入时的颜色并在单击时改变 html:
http://plnkr.co/edit/fQ5nejywl1taPSpZuBVv?p=preview
index.html:
<!doctype html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.3.0-beta.5" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div my-dom-directive>Click me!!</div>
</body>
</html>
脚本.js
var app = angular.module('app', []);
(function(){
var directive = function() {
return {
link: function($scope, element, attrs) {
element.bind('click', function() {
element.html('Clicked I am!');
});
element.bind('mouseenter', function() {
element.css('background-color', 'yellow');
});
element.bind('mouseleave', function() {
element.css('background-color', 'white');
});
}
};
};
angular.module('app').directive('myDomDirective', directive);
})
如果我不使用自调用方法来添加指令,它就可以正常工作。
谢谢。
最佳答案
尝试调用您的自调用函数。即最后的 ()。
或者替代方案:
var app = angular.module('app', []);
(function(module){
var directive = function() {
return {
link: function($scope, element, attrs) {
element.bind('click', function() {
element.html('Clicked I am!');
});
element.bind('mouseenter', function() {
element.css('background-color', 'yellow');
});
element.bind('mouseleave', function() {
element.css('background-color', 'white');
});
}
};
};
module.directive('myDomDirective', directive);
})(app);
第二种方法将模块作为参数传递给自调用函数。
关于javascript - 简单的 AngularJs 自定义指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24854463/