Should a directive talk to a controller in Angular JS?
angularjs
Solution
How I would have done it
<span enter="loadMoreTweets()">Something</span>
JS
app.controller('AppController', function ($scope) {
$scope.loadMoreTweets = function () {
console.log("Loading tweets!");
}
})
app.directive("enter", function() {
return {
link: function (scope, element, attrs) {
element.bind("mouseenter", function () {
scope.$apply(attrs.enter)
})
}
}
});
Demo: Plunker
Another way to achieve the same
app.directive("enter", function() {
return {
scope: {
callback: '&enter'
},
link: function (scope, element, attrs) {
element.bind("mouseenter", function () {
scope.$apply('callback()')
})
}
}
});
Demo: Plunker
Problem
I have been watching the videos by John Linquist and in one video he gives this as an example: ``` var app = angular.module('twitterApp', []) app.controller("AppCtrl", function ($scope) { $scope.loadMoreTweets = function () { alert("Loading tweets!"); } } app.directive("enter", function() { return function (scope, element, attrs) { element.bind("mouseenter", function () { scope.LoadMoreTweets(); }) } } ``` One thing I am wondering about is should the directive in this example talk back to the controller or would it be a better programming practice to create a service and then have the directive talk to a service? I guess I am still not sure if it is common practices for directives to talk to controllers in this way. U tube video