Skip to content

Instantly share code, notes, and snippets.

@alonronin
Created June 3, 2015 20:37
Show Gist options
  • Save alonronin/39171254e35f9b8ee66a to your computer and use it in GitHub Desktop.
Save alonronin/39171254e35f9b8ee66a to your computer and use it in GitHub Desktop.
Controlling a directive controller via service
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-app="MyApp">
<div ng-controller="MyCtrl as ctrl">
<button ng-click="ctrl.invoke()">Invoke from controller</button>
<my-directive type="cool"></my-directive>
</div>
<script id="jsbin-javascript">
angular.module('MyApp', [])
.service('$myDirective', function($rootScope){
})
.controller('MyCtrl', function($myDirective){
this.invoke = function(){
$myDirective.open('From Controller');
}
})
.directive('myDirective', function(){
return {
restrict: 'E',
scope: {
type: '@'
},
controller: function($scope, $element, $attrs, $myDirective){
this.open = function(from){
$element.find('div').text('Opened ' + from);
}
angular.extend($myDirective, this);
},
controllerAs: 'my',
bindToController: true,
template: '<h2>{{my.type}}</h2><button ng-click="my.open(\'From Directive\')">Invoke from directive</button> <div></div>',
link: function(scope, el, attrs){
}
}
})
</script>
<script id="jsbin-source-javascript" type="text/javascript">angular.module('MyApp', [])
.service('$myDirective', function($rootScope){
})
.controller('MyCtrl', function($myDirective){
this.invoke = function(){
$myDirective.open('From Controller');
}
})
.directive('myDirective', function(){
return {
restrict: 'E',
scope: {
type: '@'
},
controller: function($scope, $element, $attrs, $myDirective){
this.open = function(from){
$element.find('div').text('Opened ' + from);
}
angular.extend($myDirective, this);
},
controllerAs: 'my',
bindToController: true,
template: '<h2>{{my.type}}</h2><button ng-click="my.open(\'From Directive\')">Invoke from directive</button> <div></div>',
link: function(scope, el, attrs){
}
}
})</script></body>
</html>
angular.module('MyApp', [])
.service('$myDirective', function($rootScope){
})
.controller('MyCtrl', function($myDirective){
this.invoke = function(){
$myDirective.open('From Controller');
}
})
.directive('myDirective', function(){
return {
restrict: 'E',
scope: {
type: '@'
},
controller: function($scope, $element, $attrs, $myDirective){
this.open = function(from){
$element.find('div').text('Opened ' + from);
}
angular.extend($myDirective, this);
},
controllerAs: 'my',
bindToController: true,
template: '<h2>{{my.type}}</h2><button ng-click="my.open(\'From Directive\')">Invoke from directive</button> <div></div>',
link: function(scope, el, attrs){
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment