AngularJS:将函数传递给在其控制器中调用的指令的隔离范围?

时间:2013-10-06 23:09:45

标签: javascript angularjs angularjs-directive angularjs-scope

我试图通过“&”调用从控制器范围传递到指令的函数从指令的控制器操作。然而,Angular声称该方法未定义。在一遍又一遍地阅读我的代码,搜索互联网,然后重复这个过程后,我决定转向这里提供帮助。

这是我的控制器的相关部分。它包含我传递给我的指令的方法。

angular.module('myApp.controllers', []).controller('PostCtrl', ['$scope', 'postalService', function($scope, postalService) {
    $scope.posts = [];

    $scope.getPosts = function() {
        postalService.getPosts(function(err, posts) {
            if(err);
            else $scope.posts = posts;
        });
    };
}]);

这是我的指示。我无法调用onPost。

angular.module('myApp.directives', []).directive('compose', ['postalService', function(postalService) {
    return {
        restrict: 'E',
        transclude: false,
        replace: true,
        scope: {
            onPost: "&" //why will it not
        },
        templateUrl: "partials/components/compose-partial.html",
        controller: function($scope, postalService) {
            $scope.title = "";
            $scope.content = "";
            $scope.newPost = function() {
                postalService.newPost($scope.title, $scope.content, function(err) {
                    if(err) console.log(err + ":(");
                    else {
                        console.log("Success getting posts.");
                        //why can I not invoke onPost()??
                        $scope.onPost();
                    }
                });
            };
        },
    };
}]);

这是我的html的相关部分

<div ng-controller="PostCtrl">
    <section class="side-bar panel hide-for-small">
        <compose onPost="getPosts()"></compose>
    </section>

    <!--more, non-relevant html here-->

</div>

我知道问题不在于我的邮政服务。相反,该指令报告没有传递任何函数。为什么?

1 个答案:

答案 0 :(得分:25)

替换

<compose onPost="getPosts()"></compose>

<compose on-post="getPosts()"></compose>

它会起作用。

Angular docs说出原因:

  

指令有诸如ngBind之类的骆驼名称。该指令可以   通过将驼峰案例名称翻译成蛇案例来调用   特殊字符:, - 或_。

相关问题