gpt4 book ai didi

javascript - 为什么使用表达式对变量进行 parseInt 不显示 $scope 变量?

转载 作者:行者123 更新时间:2023-12-03 05:18:15 24 4
gpt4 key购买 nike

这是我的代码,

工作代码

var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope",
function($scope) {
$scope.value = '20';
}
]);
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="ListCtrl">
<h1> {{value}}</h1>
</div>
</body>
</html>

无法运行的代码:

var app = angular.module("app", []);
app.controller("ListCtrl", ["$scope",
function($scope) {
$scope.value = '20';
}
]);
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="ListCtrl">
<h1> {{parseInt(value)}}</h1>
</div>
</body>
</html>

通常在表达式上使用 parseInt 应该可以工作,这里有什么问题?

最佳答案

您必须解析 Controller 中的值,因为 Angular 无法将 parseInt 解析为 Angular 表达式:

另一方面,如果你真的想在 DOM 中实现这一点,最好的选择之一是使用 Angular 过滤器,例如:

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

app.filter('parseInt', function() {
return function(value) {
return parseInt(value);
};
});

app.controller("ListCtrl", ["$scope",
function($scope) {
$scope.value = '20';
}
]);
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.4.7" data-semver="1.4.7" src="https://code.angularjs.org/1.4.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-app='app'>
<div ng-controller="ListCtrl">
<h1>{{(value | parseInt) + 44}}</h1>
</div>
</body>
</html>

关于javascript - 为什么使用表达式对变量进行 parseInt 不显示 $scope 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41517371/

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