stop-start
stop-start

Reputation: 317

Calling a directive function with return value from controller

I have a directive with a form (for the example here it's a simple input), that I use several in the same page (index.html) Outside of this directive I have a button and when I click on it I want to get the data inside all the directives' input.

At first I tried using the solution from this question How to call a method defined in an AngularJS directive? but I have trouble using it with several directives at once. I also tried to use the children list with $$childHead but I understand from other posts that it is not right to do so. Anyway I'm not sure why but this last solution stopped working (it couldn't call the directive function anymore).

What would be the best approach to do this?

Here's my simplified code:

index.html:

    <div ng-repeat="item in data">
        <h1> {{item.name}} </h1>
        <my-dir info=item >/my-dir>
    </div>
    <input type="submit" value="Save" ng-click="save()" />

Directive:

    app.directive('myDir', function() {
      return {
        restrict: 'E',
        scope: {
            info: '='
        },
        templateUrl: '<input type="text" ng-model="myfield" />',
        link: function(scope, element, attrs) {
                scope.getData = function(){
                    var field_data = scope.myfield;
                    return field_data // not sure if needed
                }
        }
      };
    });

Controller:

    $scope.save= function(){
        // Call the getData function of the directive or get 
        // the data needed somehow and do something with it
    }

Upvotes: 1

Views: 1679

Answers (1)

Jakub Judas
Jakub Judas

Reputation: 787

The best way to achieve the same result would be to pass data as a two-way binding parameter to the directive, like you usually do with ng-model on the standard directives that come with angular.

... scope: { info: '=', data: '=' }, ...

and then

<my-dir info="item" data="data[0]" ></my-dir>
<my-dir info="item" data="data[1]" ></my-dir>

Upvotes: 2

Related Questions