I am absolutely new to angularjs, and I may have missed a lot of concepts. I am trying to create a modal directive for my application and something bugs me out, it is how to interact with that directive.
I am using yeoman, and it I generate a modal directive using:
yo angular:directive modal --coffee
So I had this code in my directives directory:
angular.module('myApp')
.directive('modal', () ->
templateUrl: 'views/partials/modal.html'
restrict: 'E'
link: (scope, element, attrs) ->
console.log 'link --test'
)
And now in my modal.html
partial, I inserted an anchor tag that will handle the click and alert me something.
<div><a href="" ng-click="foo()">Click Me</a></div>
Now where do I put the foo
function?
I tried something like this but with no luck
angular.module('myApp')
.directive('modal', () ->
templateUrl: 'views/partials/modal.html'
restrict: 'E'
link: (scope, element, attrs) ->
console.log 'link --test'
controller: ($scope) ->
$scope.foo = () ->
console.log 'clicked that anchor'
)
Another question, am I doing it right, I mean is it right to create a modal directive? or directives are used in a different way?
Placing
foo()
in the directive controller works well. And you're on the right track. Directives are the recommended place in Angular to do DOM manipulation - so a modal dialog is a good use case for directives.Make sure your html initializes Angular and uses the directive like this:
Here's a working fiddle using your code plus the above html (I used the template directly just for simplicity sake).