Skip to content

Instantly share code, notes, and snippets.

@danielpsf
Created September 25, 2013 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielpsf/6700536 to your computer and use it in GitHub Desktop.
Save danielpsf/6700536 to your computer and use it in GitHub Desktop.
How to call directives inside controllers (AngularJS). Run code here -> http://jsbin.com/ULIFOwI/3/
.red {
color : red !important;
}
.blue {
color : blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myController">
<input type="text" ng-model="name" />
<div my-directive>{{name}}</div>
<button ng-click="changeColor()">Change Color</button>
</div>
var myApp = angular.module('myApp', []);
myApp.controller('myController', function($scope) {
$scope.name = "Daniel";
$scope.changeColor = function() {
$scope.$emit('ChangeColor');
};
});
myApp.directive('myDirective', function(){
return function(scope, element, attrs) {
element.css({color : 'green'});
scope.$on('ChangeColor', function() {
if(element.hasClass('red')) {
element.removeClass('red');
element.addClass('blue');
} else {
element.removeClass('blue');
element.addClass('red');
}
});
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment