Deadpool Deadpool -4 years ago 98
AngularJS Question

Directive background not changing on click (through Event binding)

In the following example on clicking the div, the background must change to yellow. Not happening, also no error given. Pl, explain why!



//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>




Answer Source

When you create a directive from an element, you have to keep in mind that the newly created element uses thew following display type by default:

display: inline;

And thus, has a 0px height.

You can fix it by simply adding display: block; to the directive element:

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

Or creating the directive using an attribute:

<div my-student></div>

Here's an updated example:

//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> 

In any case, I would recommend that you stick to the angular ng-click directive for this kind of interaction, find an example below:

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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download