Ng-click binding function in compilation using AngularJS

When we try to add the ng-click function (associated with a controller action) to an element during the compilation phase, it does not work.

We can make it work if it is in a link function, but since we need a compilation 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 jsfiddle

0
source share
2 answers

It seems you missed adding .find('img')

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

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

0
source

If there is a compilation function, it is expected that it will return the binding functions (from the Directive Directive documentation). I'm not sure why the โ€œcontrollerโ€ is not working, although this is strange. Here's a workaround for your, hopefully, not too far-fetched example:

http://jsfiddle.net/fWVYD/

where the compilation function returns the binding 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 } 
-one
source

Source: https://habr.com/ru/post/1497170/


All Articles