gpt4 book ai didi

javascript - 了解 Angular 数据绑定(bind)

转载 作者:行者123 更新时间:2023-11-29 21:12:16 25 4
gpt4 key购买 nike

在阅读 Angular 数据绑定(bind)时 - 遇到建议 -

"Due to the nature of JavaScript itself and how it passes by value vs. reference, it’s considered a best-practice in Angular to bind references in the views by an attribute on an object, rather than the raw object itself."

来源:ng-book

问题:1. 绑定(bind)引用而不是对象是什么意思?

这是伴随着代码片段。

JS代码:

var module = angular.module("app", []);
//controller uses $timeout
module.controller("MyController", function ($scope, $timeout) {
var updateClock = function () {
$scope.clock = {};
$scope.clock.now = new Date();
$timeout(function () {
$scope.clock.now = new Date();
updateClock();
}, 1000);
};
updateClock();
})

HTML:

<body data-ng-app="app">
<div data-ng-controller="MyController">
<h5>Hello {{clock.now}}</h5>
</div>
</body>

问题:2. 如果我从 $timeout 外部删除此行 $scope.clock.now = new Date(); - 它不起作用。虽然 clock.now$timeout 中被分配了日期对象。为什么?

最佳答案

问题 1:

  • 它与可读性、this 和范围上下文有关
  • {{this.now}} 对比 {{clock.now}}
  • 作用域上的数据绑定(bind)可能不会触发摘要周期
  • 但即便如此,使用 $scope 也不能完全解决调试问题和可读性问题

问题 2:

这里有三个例子,我更喜欢 Controller1 的语法,它使调试更容易 imo:

var module = angular.module("app", []);
module.controller("Controller1", function ($timeout) {
var vm = this
vm.clock = {now: 'its loading'};
vm.now = new Date();
var updateClock = function () {
$timeout(function () {
vm.clock.now = new Date();
updateClock();
}, 3000);
};
updateClock();
})

module.controller("Controller2", function ($scope, $timeout) {
$scope.clock = {now: 'its loading'};
$scope.now = new Date();
var updateClock = function () {
$timeout(function () {
$scope.clock.now = new Date();
updateClock();
}, 3000);
};
updateClock();
})

module.controller("Controller3", function ($timeout) {
var vm = this
var updateClock = function () {
$timeout(function () {
try {
vm.clock.now = new Date();
} catch(e){
vm.clock = {}
vm.clock.now = 'oops'
}
updateClock();
}, 3000);
};
updateClock();
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body data-ng-app="app">
<div data-ng-controller="Controller1 as vm">
<h6>vm.clock.now {{vm.clock.now}} vm.now {{vm.now}}</h6>
<h6>vm: {{vm}}</h6>
</div>

<div data-ng-controller="Controller2">
<h6>$scope.clock.now {{clock.now}} $scope.now {{this.now}}</h6>
<h6>this is confusing {{this}}</h6>
</div>
<div data-ng-controller="Controller3 as vm">
<h1>{{vm.clock.now}}</h1>
<h6>nice scope: {{vm}}</h6>
</div>

</body>

另见:

关于javascript - 了解 Angular 数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206075/

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