从独立指令访问 $scope

Access $scope from isolated directive

我想从独立指令中更改 $scope 变量,这怎么可能?

我试过在指令范围内使用“@、=、&”语法,但无法正常工作。

这是我的简化代码

JS

app.controller('testCtrl', function($scope) {
    $scope.hello = 'hello';
}

app.directive('testDirective', function() {
    return {
        restrict: 'E',
        template: '<div>{{text}}</div>',
        scope: {},
        link: function(scope, element) {
            scope.text = 'this is my text';
            scope.hello = 'hello world!';
        }
    };
});

HTML

<body>
    {{ hello }}
    <test-directive />
</body>

这是我想要的输出

hello world!
this is my text

在HTML中,指令必须是snake-case:

<test-directive />

在您的脚本中,必须使用驼峰式定义指令:

app.directive('testDirective', function() {
});

此外,添加 ngController 指令:

<body ng-controller="testCtrl>
</body>

您可以在指令上设置 require 选项并指定父控制器。这会将控制器作为最后一个参数传递给您的 link 函数:

app.directive('testDirective', function() {
    return {
        restrict: 'E',
        template: '<div>{{text}}</div>',
        require: '^testCtrl',
        scope: {},
        link: function(scope, element, attrs, testCtrl) {
            scope.text = 'this is my text';
            testCtrl.setHello('hello world!');
        }
    };
});

请注意,您必须在控制器上创建此 testCtrl.setHello() 方法。这是因为你得到的是控制器本身,而不是它的注入范围:

app.controller('testCtrl', function($scope) {
    $scope.hello = 'hello';
    this.setHello = function(newHello) {
      $scope.hello = newHello;
    }
}

此外,如果您真的不关心严格执行控制器依赖性,您可以直接从指令访问 scope.$parent.$parent.hello

缺少的是:

  1. ng-controller 未定义
  2. @ 表示将属性作为字符串传递,= 表示将 属性 绑定到父范围内的 属性 (这是我们在这里需要的), & 表示从稍后调用的父作用域。
  3. 当调用指令时 "testDirective" 它在 HTML 中查找如下:<test-directive></test-directive> 因为 JS 中的骆驼案例需要 在 HTML.
  4. 中用“-”分隔

<body ng-controller="testCtrl"> {{ hello }} <test-directive hello-from-parent="hello"></test-directive> </body>

app.directive('testDirective', function() { return { restrict: 'E', scope: { hello: "=helloFromParent" }, template: '<div>{{text}}</div>', link: function(scope, element, attrs) { scope.text = 'this is my text'; scope.hello = 'hello world'; } } });

我设置了一个工作plnkr here