如何使用"this"声明 Angular 指令



我有以下代码:http://jsbin.com/seveba/1/edit

或者对于TL;博士

app.directive("enter", function() {
return function(scope, element) {
element.bind("mouseenter", function() {
console.log("I'm inside of you!");
});
};
});

我理解这背后的主要逻辑,但我记得我学习过如何编写这样的指令:

app.directive('directiveName', function() {
link: function(scope, element, attrs) {
// directive code goes here
}
});

蛋头上的代码好用吗?我知道链接函数是在angular编译dom之后执行的,但这并不能帮助我明确哪种方式更好。此外,我已经开始使用控制器作为语法,这使我停止在控制器上使用$scope来通过"this"将变量分配给对象。我也可以通过指令做到这一点吗?还是它们完全不同?

我想你正在寻找更多类似的东西

return {
restrict: 'A',
controller: 'SomeController',
controllerAs: 'ctrl',
template: '{{ctrl.foo}}'
link: function(){}
};

无论你的问题是哪种方式,都可以声明指令,我更喜欢返回一个对象,它对在我之后要接触代码的人来说更可读、更容易解释

The below syntax would be proper for creating a generic directive.

实施:

<div directive-name></div>

代码:

app.directive('directiveName', [function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.bind('click', function() {
alert("clicked!");
});
}
}
}]);

最新更新