[英]AngularJS Usage of Local/Global scope variables
Below is my HTML code along with JS script. 以下是我的HTML代码以及JS脚本。 I need to Change the value of "label" after the button click but it is not changing and using global values only.
单击按钮后,我需要更改“标签”的值,但它没有更改,仅使用全局值。
http://plnkr.co/edit/T4EaZglOnq8Q2UVLWNFm?p=preview http://plnkr.co/edit/T4EaZglOnq8Q2UVLWNFm?p=preview
My preview/Plnkr can be seen here.. 我的预览/ Plnkr可以在这里看到。
JS CODE: 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];
});
You are never updating your $scope.label
property inside of the click handler. 您永远不会在点击处理程序中更新
$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];
}
You are also binding label to an array of objects, not an object directly. 您还将标签绑定到对象数组,而不是直接对象。
As a result, there's no referenced value that is updated when you update your objects (since they're masked by the array) and AngularJS doesn't realize that it needs to update label. 结果,当您更新对象时(因为它们被数组掩盖了),没有引用的值被更新,并且AngularJS没有意识到它需要更新标签。
If instead you bound $scope.label
directly to $scope.year1
, you would see label properly update on the UI. 相反,如果你势必
$scope.label
直接到$scope.year1
,你会看到标签上的UI正确更新。
Another option is to use a $watch/$watchCollection and automatically update your label outside of the click handler if your year changes. 另一个选择是使用$ 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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.