1

I would like to create a directive which contains a lot of fields and one button, when user clicks at the button, the information filled should be able to pass to a search function which is outside of the directive.

var app = angular.module('myapp', []);

app.controller("myCtrl", function($scope) {

    $scope.doSearch = function(query) {
        query.order="asc";
        console.log(query); //do api call 
    }
});

app.directive('queryBuilder', function() {
    return {
        restrict: 'E',
        scope: {
            queryFn: '&'
        },
        template: "<button ng-click='directiveClick()'>Click</button>",
        replace: true,        
        link: function(scope, elm, attrs) {
          scope.directiveClick = function(){
            var query={name:"bill",age:12}
            scope.queryFn(query);
          }
        }
    }
});

view.html

<div ng-controller="myCtrl">
      <query-builder query-fn="doSearch()"></query-builder>
    </div>

the "query" parameter in doSearch() is undefined, how can I bring the query object which is inside of link function to the myCtrl?

The other method that come to my mind is to use a 2-way binding the query variable instead of passing the search function. Which way is better?

see Plunkr

1 Answer 1

2

Your method of having the directive call a function outside of its scope is perfectly valid. However, in order for the communication to work, you need to:

1, Specify the argument names when using your directive

<query-builder query-fn="doSearch(query)"></query-builder>

2, Within the directive, when calling the function, you must pass an object where the keys are the parameter names from #1.

scope.directiveClick = function(){
  var query={name:"bill",age:12}
  scope.queryFn({query: query});
}

Plunker

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.