angularjs - Should a directive talk to a controller in Angular JS? -
i have been watching videos john linquist , in 1 video gives 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 wondering should directive in example talk controller or better programming practice create service , have directive talk service? guess still not sure if common practices directives talk controllers in way.
how 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 achieve same
app.directive("enter", function() { return { scope: { callback: '&enter' }, link: function (scope, element, attrs) { element.bind("mouseenter", function () { scope.$apply('callback()') }) } } });
demo: plunker
Comments
Post a Comment