46

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!

Smamatti
  • 3,882
  • 3
  • 29
  • 42
user1879408
  • 1,768
  • 3
  • 16
  • 26

3 Answers3

46

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

jaime
  • 41,281
  • 10
  • 80
  • 52
  • Any way to pass a variable from the directive to the function passed to it? – Rojzik Oct 14 '15 at 20:31
  • 1
    Found the answer to my own question. You have to name the parameters involved. Found answer here: http://www.whatibroke.com/?p=894 – Rojzik Oct 14 '15 at 20:38
15
scope: {
    accept: "&"
}

Use lowercase letters for function names, otherwise it doesn't work.

  • 1
    Why does this kind of stuff come out only on Friday afternoons? Thanks, mate. – mccc Jul 31 '15 at 12:37
  • 8
    You don't need to use lowercase letters, just know that if you write it like 'acceptSomething' you will refer to it as 'accept-something' in markup – aw04 Nov 10 '15 at 15:42
1

Just a quick note that you dont need the wrapping function save. Just call this in the template:

'<button type="submit" x-ng-click="accept()">SAVE</button></div>',

That transposes the function call and passes the parameters as expected.

This simplifies code and makes it a lot easier to read.

Gary Blake
  • 11
  • 2