gpt4 book ai didi

javascript - Angular.js 将一个属性绑定(bind)到另一个

转载 作者:行者123 更新时间:2023-11-29 10:17:58 24 4
gpt4 key购买 nike

作为一个人为的例子,假设我有一个看起来像这样的 Angular Controller :

function OverflowController($scope) {

// initialize the count variable
$scope.count = 0;

// pretend the overflow logic is complex and doesn't belong in a filter or view
var count = parseInt($scope.count);

if (count < 100) {
$scope.overflow = "normal";
}
else if (count < 200) {
$scope.overflow = "warning";
}
else {
$scope.overflow = "error";
}

};

我有一个看起来像这样的 View :

<input ng-model="count">
<p>Count: {{count}}</p>
<p>Overflow? {{overflow}}</p>

如何将范围的溢出属性绑定(bind)到计数属性,以便在更新计数时溢出也自动更新?

最佳答案

使用 $watch: ( http://docs.angularjs.org/api/ng.$rootScope.Scope#$watch )

function OverflowController($scope) {

// initialize the count variable
$scope.count = 0;

$scope.$watch('count', function (count) {
// pretend the overflow logic is complex and doesn't belong in a filter or view

if (count < 100) {
$scope.overflow = "normal";
}
else if (count < 200) {
$scope.overflow = "warning";
}
else {
$scope.overflow = "error";
}
});
};

关于javascript - Angular.js 将一个属性绑定(bind)到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17623581/

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