单击时指令背景不变(通过事件绑定)

Directive background not changing on click (through Event binding)

在下面的示例中,单击 div,背景必须变为黄色。没有发生,也没有给出错误。请解释为什么!

//module declaration
var app = angular.module("myApp",[]);

//controller declaration
app.controller('myCtrl',function($scope){
 $scope.name = 'Peter';
});

//directive declaration
app.directive('myStudent', function(){
 return{
  template:"<div style='width:200px;height:200px;'>Hi my friend!</div>",
  link: function(scope, elem, attrs){
   elem.bind('click',function(){
    elem.css("background","yellow");

   });
  }
 }
});
<body ng-app="myApp" ng-controller="myCtrl"> 

{{name}}<br/>
<my-student></my-student>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 
</body> 

当您从元素创建指令时,您必须记住,新创建的元素默认使用以下显示类型:

display: inline;

因此,高度为 0px。

您可以通过简单地添加 display: block 来修复它;到指令元素:

<my-student style="display: block;"></my-student>

或使用属性创建指令:

<div my-student></div>

这是一个更新的例子:

//module declaration
var app = angular.module("myApp",[]);

//controller declaration
app.controller('myCtrl',function($scope){
 $scope.name = 'Peter';
});

//directive declaration
app.directive('myStudent', function(){
 return{
  template:"<div style='width:200px;height:200px;'>Hi my friend!</div>",
  link: function(scope, elem, attrs){
   elem.bind('click',function(){
    elem.css("background","yellow");

   });
  }
 }
});
<body ng-app="myApp" ng-controller="myCtrl"> 

{{name}}<br/>
<my-student style="display: block;"></my-student>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 
</body> 

无论如何,我建议您坚持使用 angular ng-click 指令进行此类交互,请在下面找到示例:

var app = angular.module("myApp",[]);

app.controller('myCtrl',function($scope){
 $scope.name = 'Peter';
});

app.directive('myStudent', function(){
 return{
  template:"<div ng-click='changeBackground()' style='height:200px;' ng-style='divStyle'>Hi my friend!</div>",
  link: function(scope, elem, attrs){
      scope.changeBackground = () => {
        scope.divStyle = { backgroundColor: 'yellow' }
      }
  }
 }
});
<body ng-app="myApp" ng-controller="myCtrl"> 

{{name}}<br/>
<div my-student></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script> 
</body>