Home > DeveloperSection > Forums > Angular.js callback function inside directive attr defined in different attr
john rob

Total Post:108

Points:756
Posted on    April-09-2013 2:22 AM

 AJAX AJAX 
Ratings:


 1 Reply(s)
 2844  View(s)
Rate this:
Hi Everyone!

So I have this directive called say, mySave, it's pretty much just this

app.directive('mySave', function($http) {
   return function(scope, element, attrs) {
      element.bind("click", function() {
          $http.post('/save', scope.data).success(returnedData) {
              // callback defined on my utils service here

              // user defined callback here, from my-save-callback perhaps?
          }
      });
   }
});
the element itself looks like this

<button my-save my-save-callback="callbackFunctionInController()">save</button>
callbackFunctionInController is for now just

$scope.callbackFunctionInController = function() {
    alert("callback");
}
when I console.log() attrs.mySaveCallback inside my-save directive, it just ives me a string callbackFunctionInController(), I read somewhere that I should 

$parse this and it would be fine, so I tried to $parse(attrs.mySaveCallback) which gave me back some function, but hardly the one I was looking for, it gave 

me back

function (a,b){return m(a,b)} 
What am I doing wrong? Is this approach flawed from the beginning?

Thanks in advance!


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    April-09-2013 7:48 AM

Hi John!

You can try as following line of code

app.directive('mySave', function($http) {
   return function(scope, element, attrs) {
      $http.post('/save', scope.data).success(returnedData) {
          // callback defined on my utils service here

          // user defined callback here, from my-save-callback perhaps?
          scope.$apply(attrs.mySaveCallback)
      }
   }
});

I hope it resolve your problem

Don't want to miss updates? Please click the below button!

Follow MindStick