被指令包裹,我如何访问它的范围? [英] Being wrapped by a directive, how can I access its scope?

查看:25
本文介绍了被指令包裹,我如何访问它的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在指令主体中访问指令的隔离范围?我的 DOM 看起来像这样:

<指令><p>boolProperty: {{boolProperty|json}}</p></指令>

boolProperty 在指令的 link 函数中赋值:

angular.module("app", []).directive("directive", function() {返回 {范围: {},链接:函数($scope){$scope.boolProperty = true;}};});

问题是,指令内的子

绑定到指令的 范围,而不是指令的孤立范围.我怎样才能克服这个问题?

点击此处查看 jsFiddle.

解决方案

你忘记了两件事:

  1. 默认情况下,AngularJS 使用属性限制,因此在您的指令定义中,您应该指定 restrict: "E"
  2. 您应该使用子作用域,而不是孤立的.所以将 scope: true 设置为从父视图范围继承.

查看更新的小提琴 http://jsfiddle.net/Y9g4q/1/.

祝你好运.

How can I access the directive's isolate scope in the directive's body? My DOM looks like this:

<div ng-app="app">    
    <directive>
        <p>boolProperty: {{boolProperty|json}}</p>
    </directive>
</div>

The boolProperty is assigned inside the directive's link function:

angular.module("app", []).directive("directive", function() {
    return {
        scope: {},
        link: function($scope) {
            $scope.boolProperty = true;
        }
    };
});

The problem is, the child <p> inside the directive binds to the directive's parent scope, not the directive's isolated scope. How can I overcome this?

Click here for jsFiddle.

解决方案

You forgot about two things:

  1. By default AngularJS uses attrubute restriction, so in your case in directive definition you should specify restrict: "E"
  2. You should use child scope, but not isolated. So set scope: true to inherit from parent view scope.

See updated fiddle http://jsfiddle.net/Y9g4q/1/.

Good luck.

这篇关于被指令包裹,我如何访问它的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆