gpt4 book ai didi

javascript - 从独立指令访问 $scope

转载 作者:行者123 更新时间:2023-11-30 17:07:10 26 4
gpt4 key购买 nike

我想从独立指令中更改 $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 选项并指定一个父 Controller 。这会将 Controller 作为最后一个参数传递给您的链接函数:

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!');
}
};
});

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

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

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

关于javascript - 从独立指令访问 $scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com