Angularjs Ng单击指令链接内的作用域

Angularjs Ng单击指令链接内的作用域,angularjs,angularjs-directive,scope,Angularjs,Angularjs Directive,Scope,你能描述一下,为什么我不能在ng click方法中得到指令的link函数中的局部变量directiveElement的值 以下是代码: (function() { "use strict"; angular .module("app") .directive("cell", ABCDirective); function ABCDirective() { return { restrict: 'E', template: '<di

你能描述一下,为什么我不能在
ng click
方法中得到指令的
link
函数中的局部变量
directiveElement
的值

以下是代码:

(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(…) ****
            };
        }
    };
}
})();
(函数(){
“严格使用”;
有棱角的
.模块(“应用程序”)
.指令(“单元”,ABCDirective);
函数ABCDirective(){
返回{
限制:'E',
模板:“更改背景”,
链接:功能(范围、元素){
var-directiveElement=元素;
scope.doSomething=函数(){
****未捕获引用错误:未定义directiveElement(…)****
};
}
};
}
})();

如果可以避免的话,我不建议在指令中应用CSS规则。相反,我建议设置一个ng类,这样样式表就可以适当地改变颜色

也就是说,看看这个源于文档的示例代码:

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);
  }
}
};

}]);
资料来源:


对于未定义的变量,首先不需要将函数参数分配给另一个变量。您可以发布实际触发此错误的代码吗?(不仅仅是错误消息代替代码)

您可以执行类似操作,更改背景颜色:

 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';
                };
            }
        };
返回{
限制:'E',
模板:“更改背景”,
链接:功能(范围、元素){
scope.myColor='红色';
scope.doSomething=函数(){
scope.myColor='蓝色';
};
}
};

您需要如下设置模块:。模块(“应用程序”,[])另外,您试图从元素中获取什么?这是我模块的一部分-模块是在其他地方创建的。第二件事-我想说改变我的按钮的背景颜色。元素指的是“单元格”,而不是按钮。所以,使用jQuery,你可以在你的链接函数中做类似的事情:$('button',directiveElement.css('background','red');谢谢您的回答,但我发现在('…',function(){…})上使用
element.on混乱。我在Angular的页面上阅读了这篇文章,无法将他们的建议应用于我的目的。