访问$范围从孤立的指令
我想从一个孤立的指令内更改一个$ 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>
编辑的,无助于解决寿。 – Inzajt 2015-01-04 10:43:32
这并不能解决隔离范围的问题并修改了父范围 – 2015-01-04 10:43:57
这里的少了什么:
- 纳克控制器没有定义
- @装置使所述属性作为字符串,=表示从父的范围结合的属性的属性(这是我们所这里需要)和&意味着从父范围传入一个函数,稍后调用。
- 当指令被称为“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
也是一个很好的解决方案,谢谢! – Inzajt 2015-01-04 11:08:55
很好的解决方案,谢谢! – Inzajt 2015-01-04 10:53:48