gpt4 book ai didi

javascript - AngularJS 本地/全局范围变量的使用

转载 作者:行者123 更新时间:2023-12-02 15:51:53 24 4
gpt4 key购买 nike

下面是我的 HTML 代码和 JS 脚本。我需要在单击按钮后更改“标签”的值,但它不会更改并且仅使用全局值。

http://plnkr.co/edit/T4EaZglOnq8Q2UVLWNFm?p=preview

我的预览/Plnkr 可以在这里看到..

JS 代码:

var app = angular.module('myApp', []);


app.controller('myCtrl', function($scope) {

$scope.firstName = "John";

$scope.lastName = "Doe";
$scope.year1=1992;
$scope.year2=1994;
$scope.year3=1996;
$scope.label=[$scope.year1,$scope.year2,$scope.year3];
$scope.splitYears = function()
{

$scope.year1=2202;
$scope.year3=2004;
$scope.year2=2001;

$scope.checking=[$scope.year1,$scope.year2,$scope.year3];
}
$scope.checking1=[$scope.year1,$scope.year2,$scope.year3];
});

最佳答案

您永远不会更新点击处理程序内的 $scope.label 属性。

$scope.splitYears = {
$scope.year1=2202;
$scope.year3=2004;
$scope.year2=2001;
$scope.label=[$scope.year1,$scope.year2,$scope.year3];
$scope.checking=[$scope.year1,$scope.year2,$scope.year3];
}

您还将标签绑定(bind)到对象数组,而不是直接绑定(bind)到对象。

因此,当您更新对象时,不会更新任何引用值(因为它们被数组屏蔽),并且 AngularJS 没有意识到它需要更新标签。

如果您将 $scope.label 直接绑定(bind)到 $scope.year1,您将在 UI 上看到标签正确更新。

另一个选项是使用 $watch/$watchCollection 并在您的年份发生变化时自动在点击处理程序之外更新您的标签。

$scope.array = [$scope.year1,$scope.year2,$scope.year3]
$scope.label = $scope.array;

$scope.$watchCollection("year1", function (newValue, oldValue) {
$scope.label = [$scope.year1, $scope.year2, $scope.year3];
});

$scope.splitYears = function() {
$scope.year1=2202;
$scope.year3=2004;
$scope.year2=2001;
$scope.checking=[$scope.year1,$scope.year2,$scope.year3];
}

关于javascript - AngularJS 本地/全局范围变量的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31792143/

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