0

Is that possible to parsing function to angularjs directive that return a templateUrl? In my case, I have this directive

.directive('forumForm', function(){
    return {
        restrict : 'C',
        scope : {
            data : '=forum',
        },
        templateUrl : '/templates/forum_form.tpl.html'
    }
});

This is my tempalteUrl

<input type="text" ng-model="data.Title" name="nameF" class="form-control" required="" ng-minlength="20" ng-maxlength="100">
<input type="" class="tagsinput" ng-model="data.tagIn" />
<button type="button" ng-click="fn(data)">Submit</button>

And, I call that via class like this

<div class="forumForm" forum="forum"></div>

Last, my controller have a function called fn

 $scope.fn = function((){ 
      alert('text') 
 })

You can see that I parsing a forum variable to my templateUrl via directive. My problem is, Is that possible to parsing a function in that directive? So if I create

 <div class="forumForm" forum="forum" fn="action(forum)"></div>

And if I click the button (In my templateUrl), It's call a function that I have written in controller. Is that possible?

1 Answer 1

1

Yes, you can use & binding for this:

The & binding allows a directive to trigger evaluation of an expression in the context of the original scope, at a specific time. Any legal expression is allowed, including an expression which contains a function call. Because of this, & bindings are ideal for binding callback functions to directive behaviors.

Example:

angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function MyCtrl($scope) {
  var ctrl = this;
  
  ctrl.forum = {}
  ctrl.log = log;
    
  function log(data){
    console.log(data);
  }; 
}])
.directive('forumForm', [function () {
        var forumForm = {
          restrict : 'EC',
          scope : {
              data : '=forum',
              fn: '&'
          },
          templateUrl : 'forum_form.tpl.html'
        }
        return forumForm;
}]);
<script src="//code.angularjs.org/1.6.2/angular.js"></script>

<div ng-app="myApp">
  <div ng-controller="MyCtrl as $ctrl">  
    <forum-form forum="$ctrl.forum" fn="$ctrl.log(data)"></forum-form>   
  </div>
  
  <script type="text/ng-template" id="forum_form.tpl.html">
    <input type="text" ng-model="data.title" />
    <input type="" class="tagsinput" ng-model="data.tagIn" />
    <button type="button" ng-click="fn({data: data})">Submit</button>
  </script>
  
</div>

Sign up to request clarification or add additional context in comments.

3 Comments

Hey, can you give me an example? I was new in angular btw
@AdiSparta check out the example. Hope it helps.
@AdiSparta accepting the answer would be much appreciated :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.