I am creating a directive
in angularJS
which will replace my custom element with some elements (pagination), the elements which are generated by the directive
has ng-click
attribute and the value of ng-click
attribute is the function of controller but the ng-click
is not working
The element is
<my-element totalCount="5"></my-element>
The controller is
.controller('AppControler',['$scope'],function($scope){
$scope.function1 = function(value){
console.log('in function1 value = '+value);
}
});
The directive is
.directive('myElement',function(){
return{
restrict: 'E',
replace: true,
scope:{
totalCount: '@'
},
template: '<ul class="pagination"></ul>`,
controller: function($scope, $element, $attrs){
$scope.draw = function(){
$($element).empty();
for (var i=1; i<=$scope.totalCount; i++){
var link = $('<li><a href="javascript:;" ng-click="function1('+i+');">'+i+'</a></li>');
$($element).append(link);
}
}
},
link: function(scope, element, attr, controller){
attr.$observe('totalCount', function(){
scope.draw();
});
}
};
});
But when I click on the <li>
element the function1
of AppController
is not invoked.
UPDATE1
Actually my directive
has the isolate-scope
and if I compile the element with $($element).append($compile(link)($scope));
then the element linked with the directive's scope but I want to compile the element with parent's scope
UPDATE2
I have made some changes in my-element like
<my-element totalCount="5" func-to-call="function1()"></my-element>
In directive
.directive('myElement',function($compile){
return{
...
...
scope:{
totalCount: '@',
funcToCall: '&'
},
...
controller: function($scope, $element, $attrs){
$scope.draw = function(){
....
....
var link = $('<li><a href="javascript:;" ng-click="function2('+i+');">'+i+'</a></li>');
$($element).append($compile(link)($scope));
....
....
}
$scope.function2 = function(value){
console.log('function2 value = '+value);
$scope.funcToCall(value);
}
}
....
....
};
});
in this case function2 of directive scope is calling and printing the value in console but $scope.funcToCall(value) is giving the error as
TypeError: Cannot use 'in' operator to search for 'function1' in <3>
UPDATE3
Created PLUNKER