Call Methods Inside Angular Directive

Let's say I have a directive with a method sayHelloWorld()that I want to call from the area from which I use the directive. How can i do this?

Also, to make things a little more complicated, how would I call this method a specific directive if I had several directives in the same area?

Plunkr shows what I want to do: http://plnkr.co/edit/E6OLgnqArBx8lrw6s894?p=preview

+4
source share
2 answers

One solution is to pass a controller object (for example:) exposedAPIinto an attribute of your directive. Then the directive will populate this object with public functions.


Plunkr


controller

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

app.controller('MainCtrl', function($scope, $timeout) {

  $scope.exposedAPI = {};

  //Later in the code...
  $timeout(function() {

    $scope.exposedAPI.elmt_1.sayHello();

    //or

    $scope.exposedAPI.elmt_2.selectIndex(42);

    //or

    $scope.exposedAPI.elmt_3.changeDirectiveContent('Yeah !');

  });

});

Directive

app.directive("byteme", function() {
  return {
    scope: {
      'api': '='
    },
    template: '<div>{{content}}</div>',
    link: function(scope, element, attrs) {

      scope.content = 'Byteme directive!'

      //Exposed functions
      scope.api[attrs.id] = {
        sayHello: function() {

          console.log("Hello World !");

        },
        selectIndex: function(index) {

          console.log("Selected index: "+index);

        },
        changeDirectiveContent: function(newContent) {

          scope.content = newContent;

        }
      };

    }
  }
});

HTML

<div byteme id="elmt_1" api="exposedAPI"></div>
<div byteme id="elmt_2" api="exposedAPI"></div>
<div byteme id="elmt_3" api="exposedAPI"></div>

<div ng-init="exposedAPI.elmt_1.changeDirectiveContent('YEAHHH')"></div> <!-- You can call API from the view directly -->
+1
source

, , , API, , ( , , )

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

/**
 * This service exposes one API method: saveDataToServer,
 * which is a methods that takes a string, and saves it
 * to some backend server.
 */
app.service('myService', function($http){

    /**
     * Save a string to some url.
     *
     * @param {string} str
     * @return Promise
     */
    this.saveDataToServer = function(str){
       return $http.post('/url/here/', {str: str});
    };
});

/**
 * This directive uses the service above, and calls 
 * the service API method inside its onAction method,
 * which only this directive can access directly.
 */
app.directive('myDirective', function(){
    return {
        restrict: 'ea',
        scope: {
        },
        templateUrl: '/my-template.html',
        controller: function(myService){

            /**
             * This is a method that you can call from this
             * directive template.
             */
            $scope.onAction = function(){

                // Inside this method, make a call to the service
                myService.saveDataToServer($scope.message).
                   then(function(res){
                       // data saved!
                   });
            };
        }
    };
});

// The template (/my-template.html)
<div>
    <input type="text" ng-model="message">
    <button ng-click="onAction()">Save</button>
</div>

// Your main template (/index.html)
<my-directive></my-directive>

:

app.controller('MyOtherController', function(myService){
    $scope.onSomeAction = function(str){
        myService.saveDataToServer(str).
           then(function(res){
               // data saved!
           });
    };
});

// Some template under the scope of MyOtherController
<div ng-controller="MyOtherController">
    <button ng-click="onSomeAction('hello world')">Hello</button>
</div>

, , . , . $controller , , , :

app.controller('MyController', function($scope){
    $scope.colors = [
       {color: 'Red'},
       {color: 'Green'},
       {color: 'Blue'}
    ];
});

app.directive('MyDirective', function(){
    return {
        scope: {
            colors: '='
        },
        templateUrl: '/my-template.html'
    };
});

// Template file: my-template.html
<div>
   <select ng-options="opt.color for opt in colors">
</div>

// index.html
<my-directive colors="colors"></my-directive>

, , , , , , .

, , , . .

+2

All Articles