2015-01-04 79 views
1

我想從一個孤立的指令內更改一個$ 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 

回答

2

您可以設置在指令中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

+0

很好的解決方案,謝謝! – Inzajt 2015-01-04 10:53:48

0

在HTML中,指令必須在蛇案:

<test-directive /> 

在腳本中,該指令必須在駱駝的情況下進行定義:

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

此外,添加了ngController指令:

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

編輯的,無助於解決壽。 – Inzajt 2015-01-04 10:43:32

+0

這並不能解決隔離範圍的問題並修改了父範圍 – 2015-01-04 10:43:57

0

這裏的少了什麼:

  1. 納克控制器沒有定義
  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 here

+0

也是一個很好的解決方案,謝謝! – Inzajt 2015-01-04 11:08:55

相關問題