2

This is a followup to this question. I have the same setup:

Angular scope is shared for all modules and controllers

So root module, controllers and directives. Now to the question:

I have a service, that has this written inside:

firstModule.factory("firstService", function () {
   return {   
       $('.mainitems').click(function () {               
            alert("hi")
        });
   };
});

And a directive, that is nested inside other directive:

    secondModule.directive("secondDirective", function () {
    return {
        templateUrl: "./myurl",
        restrict: "E",
        replace: true,
        compile: function (tElement, tAttrs, controller) {
            return {

            }
        }
    }
});

When I have the line : restrict: "E", the click function does not work, but when I remove it, then it works.

Any idea why this may be the problem? It's a strange thing, after a day of debugging I found the issue.

Community
  • 1
  • 1
Jaanus
  • 16,161
  • 49
  • 147
  • 202

2 Answers2

2

In fact manage dom manipulation in factory is a bad pattern ! All DOM manipulation have to be place in directive so for a click it's ng-click

For example :

<div ng-controller="MyController">
    <div ng-click="click()"></div>
</div>

Where click() is a function fo your scope. So you have your controller like this :

secondModule.controller('MyController', function($scope){

    $scope.click = function(){
      //do what you want
    };

});

When you'll click on your div it will call the click function in your controller

Your directive should be :

secondModule.directive("secondDirective", function () {
return {
    template: "<div ng-click='click()'><a>Click here</a></div>",
    restrict: "E",
    replace: true,
    link: function (tElement, tAttrs, controller) {
    }
}
});

And you html like that :

<second-directive></second-directive>

Working plunkr here : http://plnkr.co/edit/DmkQTp?p=preview

Thomas Pons
  • 7,709
  • 3
  • 37
  • 55
1

When you provide restrict: "E" (element) as a configuration option ng will expect a custom tag like: <second-directive></second-directive> for this directive to be applied. When you remove it, it defaults to "A" (attribute), which may be what you are using as declaration to apply this directive.

tikider
  • 540
  • 3
  • 12