prozaek.prozaek prozaek.prozaek - 1 month ago 5
AngularJS Question

how realize click event on directive?

Please help fix the script.

i make simply directive:

angular.module('menus', [])
.directive("epMenu", ['$timeout', '$state',
function ($timeout, $state) {
return {
link: function (scope, element, attrs) {
scope.goTo = function(link) {
console.log('go to', link);
};

var navigationElem = angular.element("<div class='ep-menu-navigation'><li ng-click='scope.goTo('main')'>qwerty</li></div>");

angular.element('body').append(navigationElem);
},

restrict: "EACM"
}
}]);


but it does not work. I need to when you press the button, start function goTo()

Now the console following error message:


VM436 angular.js:12520 Error: [$injector:unpr] Unknown provider: $stateProvider <- $state <- epMenuDirective


live example

Answer

$state is a provider that is registered in the ui.router module, so you have to lay that dependency:

angular.module('menus', ["ui.router"])

Also, if you are building the template dynamically in the link function, you have to compile it so that angular can apply its actions to it:

.directive("epMenu", ['$timeout', '$state', '$compile',
    function ($timeout, $state, $compile) {
        return {
            link: function (scope, element, attrs) {
                scope.goTo = function(link) {
                    console.log('go to', link);
                };

                var navigationElem = angular.element("<div class='ep-menu-navigation'><li ng-click='goTo('main')'>qwerty</li></div>");

                $compile(navigationElem)(scope, function(cloned){
                    angular.element('body').append(cloned);
                });
            },
            restrict: "EACM"
        }
    }]);

You also had some other errors in your code:

  • Missing the angular ui router script
  • Using scope.goTo instead of just goTo
  • Not escaping the quotes in the goTo function
  • Using jqLite, you cannot use angular.element('body'), instead use the $document service

Here is a working example.