[英]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>
這里缺少的是:
<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'; } } });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.