在以下单击 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>
关于javascript - 单击时指令背景不会更改(通过事件绑定(bind)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42531939/