版本:AngularJS v1.7.7
浏览器:Chrome
背景:我想要在指令“控制器this
”点上定义的属性与在父控制器的作用域上定义的参数进行双向绑定
代码使我感到困惑,它具有神奇的性能:
undefined
,并且父控制器可以更改指令,但指令不能更改父控制器
angular.module('app', []).controller('mainController', function($scope) {
$scope.text = 'main'
$scope.bindText='hello'
$scope.change = () => {
$scope.bindText='llllllll'
}
}).directive('testDirective', function() {
return {
restrict: 'E',
template: '<p> {{vm.bindText}} this is directive<p>',
bindToController: true,
scope:{
bindText:'='
},
controllerAs: 'vm',
controller: function() {
const vm= this;
console.log(vm.bindText)
vm.bindText = 'ggg'
},
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<!DOCTYPE html>
<html lang="en" ng-app='app'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div ng-controller="mainController">
<test-directive scope-fuc="ditConsoleScope" bind-text="bindText"></test-directive>
<button ng-click="change()">{{ text }} {{ bindText }}</button>
</div>
</body>
</html>
,但是如果您添加$onInit
,如下所示:
vm.$onInit = function() {
console.log(vm.bindText)
vm.bindText = 'ggg'
}
这行得通,为什么我需要在指令中使用组件挂钩函数?
bindToController
和scope
之间的关系,如果我删除上面代码中的scope
属性,它们将不再具有绑定,即使您添加
$onInit
,为什么?
如果您删除scope
并像这样设置bindToController
:
.directive('testDirective', function() {
return {
restrict: 'E',
template: '<p> {{vm.bindText}} this is directive<p>',
bindToController: {
bindText: "="
},
controllerAs: 'vm',
controller: function() {
const vm= this;
console.log(vm.bindText)
vm.bindText = 'ggg'
},
}
})
与第一个情况相同
为什么?为什么根本没有规则?