javascript - Proper "Angular" way to pass behavior to directive? -


when looking information regarding angular directives , passing behavior directives, ended being pointed in direction of method binding on isolate scope, i.e.

scope: {   something: '&' } 

the documentation functionality bit confusing, , don't think it'll end doing want.

i ended coming snippet (simplified brevity), works passing scope function in homectrl, , directive it's work , calls function. (just incase matters, real code passes promise directive).

angular.module('app', []);    angular.module('app')    .directive('passingfunction',      function() {        var changefn,          bump = function() {            console.log('bump() called');            internalvalue++;            (changefn || function.prototype)(internalvalue);          },          internalvalue = 42;          return {          template: '<button ng-click="bump()">click me!</button>',          scope: {            onchange: '<'          },          link: function(scope, element, attrs) {            if (angular.isfunction(scope.onchange)) {              changefn = scope.onchange;            }              scope.bump = bump;          }        };      })    .controller('homectrl',      function($scope) {        $scope.receive = function(value) {          console.log('receive() called');          $scope.receiveddata = value;        };      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.4/angular.min.js"></script>  <div ng-app="app" ng-controller="homectrl">    <passing-function on-change="receive"></passing-function>    <p>data directive: {{receiveddata}}</p>  </div>

is proper "angular" way of achieving this? seems work.

what need pass function directive. i'll make small example.

on controller:

$scope.thisfn = thisfn(data) { console.log(data); }; 

in html:

<my-directive passed-fn="thisfn()"></my-directive> 

on directive:

.directive('mydirective', [   () => {     return {       restrict: 'e',       scope: {         passfn: '&'       },       template: '<div id="mydiv" ng-click="passfn(data)"></div>',       link: (scope) => {            scope.data = "test";       }     }   }]); 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -