Yichz
Yichz

Reputation: 9671

Angular pass variables from directive to controller

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

Upvotes: 1

Views: 67

Answers (1)

Anid Monsur
Anid Monsur

Reputation: 4538

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

Upvotes: 2

Related Questions