Anonymous Anonymous - 5 months ago 13
AngularJS Question

AngularJs directive, scope with value and function

I have a directive

myEditable
that toggle a
<div>
with an
<input type=text>
to allow inline edition :

<my-editable value="vm.contact.name"></my-editable>


I was happy with it until I read some articles that say that
$scope.$apply
should not be used. I'm using it when the user save his changes to update the model (
vm.contact.name
in my case) :

function save() {
scope.$apply(function(){
scope.value = editor.find('input').val();
});
toggle();
}


But since it is a bad thing, I would like to pass a callback method to my directive. This callback must be called with the new value when the user save his changes. However, it seems that I cannot add two fields to the directive scope :

return {
restrict: 'EA',
scope: {
value: '=value'/*,
onSave: '&onSave'*/
},
link: function(scope, element, attr) {
// ...
element.find('.save').click(function(){
save();
});

// Declaration of `save` as above.
}
}


If I uncomment
onSave
then the value is never received and
onSave
is undefined.

My question is, how can I give a value and a callback method to a directive ?
And, as bonus, how can I pass parameters to the callback ?

Thanks

Answer

You can pass 'n' number of fields in directives isolated scope.

If you want to pass a function use &. Keep this in mind if your property name is onSave then in the view use it like this on-save.

You directive should look like below

app.directive('dir',function(){
  return {
  restrict: 'EA',
  scope: {

    onSave: '&'
  },
  link: function(scope, element, attr) {
    // ...
    debugger
    console.log(scope.onSave)
    scope.onSave();

    // Declaration of `save` as above.
  }
}

})

In the view you can pass the function like below

 <dir on-Save='abc()'/>

OR

 <dir on-save='abc()'/>
Comments