0

When we try to add an ng-click function (linked to a controller action) onto an element during the compile phase, it is not working.

We can get it working if it is in the link function, but as we need a compile function, the link is not called.

Can anyone help?

HTML:

<div ng-app="editApp" ng-controller="podCtrl">
  <a href="" data-model="image" data-cms-link-pod>
    <img />
  </a>
</div>

JS:

var module = angular.module('editApp', []);

module.directive('cmsLinkPod', function () {
    return {
        restrict: 'A',
        scope: {
            pod: '=model',
        },
        controller: function ($scope) {
            $scope.ohai = function () {
                console.log('click triggered')
                event.preventDefault();
            };
        },
        compile: function (element, attrs, transclude) {
            element.find('img').attr('ng-src', '{{pod.src}}');
            element.attr('data-ng-click', 'ohai()');
        }
    };
});

module.controller('podCtrl', ['$scope', function($scope) {
    $scope.image = {
        src: 'http://placekitten.com/100/100'
    }
}]);

See this jsfiddle

2
  • 1
    jsfiddle.net/js8N9/1 - u missed .find('img') Commented Jun 14, 2013 at 8:43
  • 1
    @Atrix1987 please add it as answer Commented Jun 14, 2013 at 9:02

2 Answers 2

0

it seems you missed to add .find('img')

Check http://jsfiddle.net/js8N9/2/

Updated: http://jsfiddle.net/js8N9/3/

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I could have done that, but the point was I needed to add the click to the anchor, not the image. Maybe it was not the greatest example as there would be no difference in this case, but the real world example is much more complicated and I cannot just put the click on the contents.
if thats the case why not simply add the ng-click to anchor tag see th updated fiddle
-1

If there is a compile function, it's expected that it will return the linking functions (from the AngularJS Directive documentation). I'm not sure why "controller" isn't running though - that's strange. Here's a workaround for your hopefully not too contrived example:

http://jsfiddle.net/fWVYD/

where the compile function returns the linking function.

compile: function (element, attrs, transclude) {
    ...
    //return linking function (can specify pre and post link)
    return function($scope) {
      $scope.ohai = function () {

      };  
    }
},
link: function($scope, $el, $attrs) {
    //will not be run
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.