简体   繁体   中英

AngularJS; Send a function from the parent into directive scope

I'm creating a reusable component/widget as a directive using a template and isolated scope. I'd like to be able to also send a callback into the directive and call it in the widget. Is this possible? Something like...

mainView template: <my-widget callback="someFunction"></my-widget>

directive:

return {
    restrict: 'E',
    scope: {
        callback: '='
    },
    templateUrl: '/partials/widget.html',
}

And the template:

<input type="text" ng-change="callback()" />

So when the widget value is changed, it triggers the callback function that was passed in the main view

What you're looking for is & . Quoting the old angular docs : "& or &attr - provides a way to execute an expression in the context of the parent scope".

Try this as your directive code:

return {
    restrict: 'E',
    scope: {
        callback: '&'
    },
    templateUrl: '/partials/widget.html',
}

You can also $watch for it in the link or controller.

.directive('myDirective', function() {

  return {
    restrict: 'E',
    link: function(scope, element, attrs) { {
      scope.$watch(attrs.myDirective, function(value){ ... });
    }
   ...

事实证明,我需要按照建议进行操作,并使用&而不是=,但是在我向输入中也添加ng-model之前,这仍然行不通:

<input type="text" ng-model="myValue" ng-change="callback()" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM