5

我对使用 AngularJS 相当陌生,我想做的是创建一个指令并从其中的父范围调用函数。我能够做到这一点,但我似乎无法弄清楚如何通过表达式将数据从隔离范围传递到父范围。Angular Developer guide 中对此的解释有点混乱。

指令:

app.directive('myDir', function() {
    return {
        restrict: 'E',
        template: '<div ng-click="parentFunc(someValue)"><div>', 
        scope: {
           parentProp: '=property',
           parentFunc: '&func'
        },
        link: function(scope, element, attrs) {

        }
    }
});

标记:

<my-dir prop="foo" func="bar(someValue)"></my-dir>

控制器:

app.controller('TstCtrl', function($scope) {
    $scope.foo = 'test';
    $scope.bar = function(value) {
       console.log(value);
    };
});

在此先感谢您的帮助!

4

1 回答 1

11

There may be other ways to do this but see this fiddle where you would pass in an object to the function using the same parameter names passed into your func attribute.

    link: function(scope, element, attrs) {
        scope.parentFunc({someValue:'testing'});            
    }

So in this case since you called bar(someValue) in your func attribute you would want to pass in an object with someValue in your link function. You're calling parentFunc because that's what &func is linked to in your isolate scope.

于 2012-10-26T19:01:14.077 回答