0

Assume that I have a directive like this

<div my-directive callback='doSomething(myArg)'></div>

angular.module('directives').directive('myDirective', function() {
   return {
      restrict: 'A',
      scope: {
        callback: '&'
      },
      link: function(scope, element, attrs) {
        element.bind('someEvent', function() {
          scope.callback({myArg: 'bla'});
        });
      }
   }
});

If I want to pass a parameter to my scope's function, I have to do scope.callback({myArg: 'bla'}). I wonder if there's a way pass the argument without having to specify its name?

2
  • There's no other way, you could use a service, or 2 way data binding through the isolate scope but those have even more ceremony than simply passing in a named parameter. Commented Feb 10, 2014 at 8:53
  • I think you could use a pub/sub service, I created one for Angular if you're interested. Commented Feb 10, 2014 at 13:31

1 Answer 1

1

Use can use shared service in this case and inject it to directive:

    angular.module("yourAppName", []).factory("mySharedService", function($rootScope){

        var mySharedService = {};

        mySharedService.values = {};

        mySharedService.setValues = function(params){
            mySharedService.values = params;
            $rootScope.$broadcast('dataPassed');
        }

        return mySharedService; 
   });

And after inject it to directive. For example:

app.directive('myDirective', ['mySharedService', function(mySharedService){
    return {
        restrict: 'C',
        link: function (scope, element, attrs) {
            mySharedService.setValues(//some value//);
        }
    }
 }]);

Then, you can get necessary value in controller.

function MyCtrl($scope, mySharedService) {
   $scope.$on('dataPassed', function () {
       $scope.newItems = mySharedService.values;
   });
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.