Created
September 25, 2013 14:34
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.red { | |
color : red !important; | |
} | |
.blue { | |
color : blue !important; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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