加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 如何将变量注入指令的范围?

发布时间:2020-12-17 10:25:54 所属栏目:安全 来源:网络整理
导读:假设我有一个看起来像这样的指令: directive('attachment',function() { return { restrict: 'E',controller: 'AttachmentCtrl' }}) 这意味着我可以像这样写一个’attachment’元素列表: attachment ng-repeat="a in note.getAttachments()" pAttachment I
假设我有一个看起来像这样的指令:
directive('attachment',function() {
    return {
        restrict: 'E',controller: 'AttachmentCtrl'
    }
})

这意味着我可以像这样写一个’attachment’元素列表:

<attachment ng-repeat="a in note.getAttachments()">
    <p>Attachment ID: {{a.id}}</p>
</attachment>

在上面的代码片段中,我们假设note.getAttachments()返回一组简单的javascript对象哈希值.

因为我为指令设置了一个控制器,所以我可以内联调用该控制器的作用域函数.

这是控制器:

function AttachmentCtrl($scope) {
    $scope.getFilename = function() {
        return 'image.jpg';
    }
}

这里是修改后的HTML,当我们包含对内联的$scope.getFilename函数的调用时(新的第2段):

<attachment ng-repeat="a in note.getAttachments()">
    <p>Attachment ID: {{a.id}}</p>
    <p>Attachment file name: {{getFilename()}}
</attachment>

但是,这没用.这将只打印相同的字符串“image.jpg”作为每个附件的文件名.

实际上,附件的文件名基于附件ID.因此ID为“2”的附件的文件名为“image-2.jpg”.

所以我们的getFilename函数需要修改.我们来解决它:

function AttachmentCtrl($scope) {
    $scope.getFilename = function() {
        return 'image-' + a.id + '.jpg';
    }
}

但是等等 – 这不会奏效.范围中没有变量a.由于ng-repeat,我们可以使用变量a inline,但变量不能绑定到指令的作用域.

所以问题是,如何使范围可用?

请注意:我意识到在这个特定的例子中,我可以打印图像 – {{a.id}}.jpg inline.但这并没有回答这个问题.这只是一个极其简化的例子.实际上,getFilename函数太复杂而无法内联打印.

编辑:是的,getFilename可以接受一个参数,这将起作用.但是,这也没有回答这个问题.我仍然想知道,没有解决方法,是否可以在不使用内联的情况下进入范围.

例如,可能有一种方法可以将其直接注入控制器,因此它将被写为:

function AttachmentCtrl($scope,a) { ... }

但是我从哪里传递它?我可以在指令声明中添加一些内容吗?也许我可以在ng-repeat旁边添加一个ng- *属性?我只是想知道它是否可能.

But wait — this won’t work. There is no variable “a” in the scope. We can use the variable a inline thanks to the
ng-repeat,but that a variable isn’t available to the scope bound to
the directive.

实际上,变量a在与指令控制器相关联的范围内.由指令创建的每个控制器获取由ng-repeat迭代创建的子范围.这样可行(注意$scope.a.id):

function AttachmentCtrl($scope) {
    $scope.getFilename = function() {
        return 'image-' + $scope.a.id + '.jpg';
}

这是一个显示控制器范围,指令范围和ngRepeat范围的fiddle.

“If multiple directives on the same element request new scope,only one new scope is created. ” — 07001,section “Directive Definition Object”

在您的示例中,ng-repeat正在创建一个新范围,因此该相同元素上的所有指令都获得相同的新(子)范围.

此外,如果您遇到需要将变量放入控制器的情况,使用属性将比使用ng-init更好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读