如何从控制器中的指令获取范围变量?

How to get a scope variable from a directive in a controller?

我正在构建一个自定义指令,我想在其中从我的控制器访问独立的范围变量。

这是 html 的样子:

<display-user-comment userId="user.id"></display-user-comment>

我的指令如下所示:

    app.directive('displayUserComment', function () {
        return {
            restrict: 'E',
            templateUrl: 'user_comment.html',
            scope: {
                userId: '='
            },
            controller: 'UserCommentController as userCmtCtrl'
        };
    })

这是我的控制器的样子:

app.controller('UserCommentController', [
    '$scope',
    function ($scope) {

    //How to get access to userId ??
}]);

如何在我的控制器中访问隔离变量 userId?

这里是 plunker url http://plnkr.co/edit/9Lh9sPp8o7gZLs1h8RDs?p=preview

您使用了错误的属性名称。当您驼峰式排列一个指令属性时,它会用破折号代替 (userId = user-id)。这是更新后的 plunkr http://plnkr.co/edit/I8TWzTBh7IvZZxtaQ5sk?p=preview

 <display-user-comment user-id="23"></display-user-comment>

将 userId 更改为 html 中的用户 ID。 angular“规范化”属性名称,因此在您的 html 中作为属性名称的 user-id 在您的指令中变为 scope.userId。

更多信息https://docs.angularjs.org/guide/directive:

Angular normalizes an element's tag and attribute name to determine which elements match which directives. We typically refer to directives by their case-sensitive camelCase normalized name (e.g. ngModel). However, since HTML is case-insensitive, we refer to directives in the DOM by lower-case forms, typically using dash-delimited attributes on DOM elements (e.g. ng-model).

The normalization process is as follows:

Strip x- and data- from the front of the element/attributes. Convert the :, -, or _-delimited name to camelCase.