Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: How to pass arguments/functions to a directive?

Look at this Fiddle, what do I have to change, that the expressions in the template get evaluated using the arguments I defined in the HTML? The SAVE-button should call the blabla()-function of the controller, since I pass it?

var myApp = angular.module('MyApp',[]) myApp.directive('editkeyvalue', function() {     return {         restrict: 'E',         replace: true,         scope: {             accept: "expression"         },         template : '<div><label class="control-label">{{key}}</label>' +         '<label class="control-label">{{key}}</label>' +           '<input type="text" ng-model="value" />'+         '<button type="button" x-ng-click="cancel()">CANCEL</button>' +         '<button type="submit" x-ng-click="save()">SAVE</button></div>',        controller: function($scope, $element, $attrs, $location) {         $scope.save= function() {           $scope.accept();         };       }     } }); 

I do not really see through that. Thanks for help!

like image 961
user1879408 Avatar asked Dec 05 '12 14:12

user1879408


People also ask

How does directive work in AngularJS?

AngularJS directives are extended HTML attributes with the prefix ng- . The ng-app directive initializes an AngularJS application. The ng-init directive initializes application data. The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.


1 Answers

You can set two way data binding with property: '=' as Roy suggests. So if you want both key and value bound to the local scope you would do

scope: {     key: '=',     value: '=' }, 

Since you are passing these values, you have access to them in your directive's controller. But in case you want to run a function in the context of the parent scope, which seems to be what you want to do with the accept attribute, then you would need to tell angular like this

scope: {     accept: "&" } 

Now, from your save method you could call the function passed via accept

controller: function($scope, $element, $attrs, $location) {     $scope.save= function() {               $scope.accept()     }; } 

Here's a jsfiddle

like image 82
jaime Avatar answered Oct 19 '22 13:10

jaime