下面是我的HTML代码和JS脚本。我需要在按钮单击后更改“标签”的值,但它不会更改并仅使用全局值。
http://plnkr.co/edit/T4EaZglOnq8Q2UVLWNFm?p=preview
我的预览/ Plnkr可以在这里看到..
JS CODE:
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];
});
答案 0 :(得分:2)
您永远不会更新点击处理程序中的$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];
}
您还将标签绑定到对象数组,而不是直接绑定对象。
因此,更新对象时没有更新的参考值(因为它们被数组掩盖)并且AngularJS没有意识到它需要更新标签。
如果您将$scope.label
直接绑定到$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];
}