你能描述一下,为什么我不能在directiveElement
方法的link
指令函数中得到局部变量ng-click
的值?
这是代码:
(function() {
"use strict";
angular
.module("app")
.directive("cell", ABCDirective);
function ABCDirective() {
return {
restrict: 'E',
template: '<div><button ng-click="doSomething()">Change background</button></div>',
link: function(scope, element) {
var directiveElement = element;
scope.doSomething = function() {
**** Uncaught ReferenceError: directiveElement is not defined(…) ****
};
}
};
}
})();
答案 0 :(得分:2)
你可以这样做,改变背景颜色:
return {
restrict: 'E',
template: '<div><button ng-style="{\'background-color\':myColor}" ng-click="doSomething()">Change background</button></div>',
link: function(scope, element) {
scope.myColor = 'red';
scope.doSomething = function() {
scope.myColor = 'blue';
};
}
};
答案 1 :(得分:0)
如果可以避免,我建议不要在指令中应用CSS规则。相反,我建议设置ng-class,以便样式表可以适当地改变颜色。
那就是说,看看这个来自docs的示例代码:
angular.module('dragModule', [])
.directive('myDraggable', ['$document', function($document) {
return {
link: function(scope, element, attr) {
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: 'lightgrey',
cursor: 'pointer'
});
element.on('mousedown', function(event) {
// Prevent default dragging of selected content
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.pageY - startY;
x = event.pageX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
}
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
}
};
}]);
来源:https://docs.angularjs.org/guide/directive
对于未定义的变量,您不需要首先将函数参数分配给另一个变量。你可以发布实际触发此错误的代码吗? (不只是代替代码的错误信息)