0

I know that you can bind a directive by:

Html:

<mydirective />

Js:

app.directive('mydirective', function () {})

However I saw this SO answer. So is it possible to bind a directive like?

Html:

<input ng-something="foo()">

Js:

app.directive('ngSomething', function () {})

Or I should always have template: inside the directive so as I inject the code. My purpose is to bind a ng-keydown on an existing input:

This does not work :

<input type="text", placeholder="Search stuff" ng-model="searchBar" ng-keydown="dosomthg()">

So I'm trying based on the above answer:

<input type="text", placeholder="Search stuff" ng-model="searchBar" ngSearchbar="dosomthg()">

Community
  • 1
  • 1
Diolor
  • 13,181
  • 30
  • 111
  • 179

2 Answers2

1

should [I] always have template?

No. Apart from modifying DOM structure, directives can provide pure behavior as well.

So is it possible to bind a directive like: my-directive="someFunction()"

Yes. In the simplest scenario it goes like this PLNKR. To your directive you can pass delegates to functions from parent scope and even anonymous angular expression. Take a look and play a bit with it! If you want to know more about it try to read angular docs.

artur grzesiak
  • 20,230
  • 5
  • 46
  • 56
  • Thank you. I also gave `my-directive="someFunction($event)"` to pass the event resources. I was reading the docs but Ajs are not the best :) – Diolor Nov 29 '13 at 01:18
0

You don't always have to include a template. But if you were to include a template, you can do it this way:

directive:

app.directive('ngSomething', function () {
  return {
    restrict: 'E', // means element
    template: '<input type="text", placeholder="Search stuff" ng-model="searchBar" ng-keydown="dosomthg()">'
  }
});

html:

<ng-something></ng-something>

dosomthg():

  $scope.dosomthg = function() {
    $scope.name = 'mate';
};

http://plnkr.co/edit/nV57jx?p=preview

mnsr
  • 12,337
  • 4
  • 53
  • 79