在以下单击div的示例中,背景必须更改为黄色。没有发生,也没有给出错误。 Pl,解释原因!
//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>
答案 0 :(得分:3)
从元素创建指令时,必须记住新创建的元素默认使用以下显示类型:
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");
});
}
}
});
&#13;
<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>
&#13;
无论如何,我建议您坚持使用角度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' }
}
}
}
});
&#13;
<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>
&#13;