簡體   English   中英

從隔離指令訪問$ 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

您可以在指令上設置require選項並指定父控制器。 這會將控制器作為最后一個參數傳遞給鏈接函數:

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

在HTML中,偽指令必須為蛇形:

<test-directive />

在腳本中,必須在駝峰式的情況下定義指令:

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

另外,添加ngController指令:

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

這里缺少的是:

  1. ng-controller未定義
  2. @表示將屬性作為字符串傳遞,=表示將屬性綁定到父級作用域中的屬性(這是我們在這里所需要的),&表示從父級作用域傳入函數以供以后調用。
  3. 當該指令稱為“ testDirective”時,它在HTML中的外觀如下: <test-directive></test-directive>因為JS中的駝峰大小寫需要在HTML中用“-”分隔。

<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM