Tariiq Henry Bbosa Tariiq Henry Bbosa - 4 months ago 12
AngularJS Question

applying scopes on angular directives and calling object function

This code works fine and uses the parent controller scope;

"<button type='button' post-random-feed >Post review</button>"

.directive("postRandomFeed",['config',function(){
return function(scope,element.attrs){

element.bind("click", function(){
scope.name ="henry";
console.log(element);
});



}
}]);


my problem is that i want to define an isolated scope and return an object instead of a function from the directive. This is my code

"<button type='button' post-random-feed >Post review</button>"

.directive("postRandomFeed",['config',function(){
return {

restrict :"A",

scope : {

},

irony : function(element, attrs)
{
element.bind("click", function(){
console.log(element);
});


}
};
}]);


How do i call the irony function so that the element registers the click event any mistakes please correct me. Thank you

Answer

Is this what you want to do? You can register a callback to the controller:

html:

<button type='button'  post-random-feed on-irony="onControllerFn">Post review</button>

directive:

.directive("postRandomFeed",['config',function(){
        return { 
            restrict :"A",
            scope : {},
            link : function(scope, element, attrs) {   
                $timeout(function () {
                   scope.$emit(attr.onIrony);
                });
            });

        }
    };
}]);

and in controller you can do:

$scope.$on('onControllerFn', function(event) {
    // your code here
});
Comments