我正在使用 AngularJS,我想创建一个仅在用户注册时才执行操作的按钮。如果用户未注册,则会打开带有特定消息的注册工具提示。这是按钮标记:
<button signup-tooltip="submitForm()" signup-message="Please sign in to submit the form">submit form</button>
注册工具提示模板如下所示:
<div class="signup-tooltip-view">
....Many elements
....
</div>
重要的是注册工具提示必须在按钮上方打开。
我的注册工具提示如下所示:
module.directive('signupTooltip', function() {
return {
scope: {
action: '&signupTooltip',
message: '@signupMessage'
},
templateUrl: 'path/to/signup/tooltip.html',
link: function(scope, element, attrs) {
function calculatePosition() {
// This method calculates the position of the tooltip (above element)
var top, left;
....
....
....
return {
top: top,
left: left
};
}
element.click(function() {
if (user.isRegistered) {
scope.action();
} else {
var tooltipPosition = calculatePosition();
// Here I need a reference for the template element <------PROBLEM
var tooltipTemplate = ..... HOW TO GET THE TOOLTIP ELEMENT
tooltipTemplate
.appendTo(element.parent())
.css(tooltipPosition);
}
});
}
};
});
在指令内,我需要编译元素(从中创建的元素)的引用。我怎样才能得到它(请记住我需要使用模板编译signupMessage)?
这种用例(工具提示)的 Angular 方式是什么?
最佳答案
您应该更多地使用框架,而不是围绕它。
这是做事的“Angular 方式”:
JS:
var template = '<button ng-click="onClick()">submit form</button>\
<div class="signup-tooltip-view" ng-bind="message" ng-show="!!position" style="top:{{ top }}px;left: {{ left }}px">';
module.directive('signupTooltip', function() {
return {
restrict: 'E',
scope: {
action: '&',
message: '@'
},
template: template,
link: function(scope, element, attrs) {
function calculatePosition() {
// This method calculates the position of the tooltip
var top, left;
return {
top: top,
left: left
};
}
scope.onClick = function() {
if (user.isRegistered) {
scope.action();
} else {
scope.position = calculatePosition();
}
};
}
};
});
当然,您可以将模板放在单独的文件中,并使用 templateUrl 属性引用它,而不是提供字符串。
HTML:
<signup-tooltip action="submitForm()" message="Please sign in to submit the form">
关于javascript - 获取 AngularJS 指令中的模板元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26330407/