我是Angularjs的新手,通过做一些任务来练习它。这里我在控制器中创建一个对象,在我的网页中创建对象值。但是这里ng-show没有评估下面的表达式。但是如果我在控制器中创建一个变量 $ scope.ngshow = false; 它将起作用。请帮助我为什么下面的代码不起作用。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show = "a.name"> Name {{a.name}} </li>
<li ng-show = "a.id"> Id {{a.id}}</li>
<li ng-show = "a.address"> Address {{a.address}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name' : 'false',
'id' : 'true',
'address' : 'false'
};
});
</script>
<p>ng-show didnt accept expressions.</p>
</body>
</html>
感谢您宝贵的时间。
答案 0 :(得分:1)
您不应将true
或false
用作字符串
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name' : false,
'id' : true,
'address' : false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show = "a.name"> Name {{a.name}} </li>
<li ng-show = "a.id"> Id {{a.id}}</li>
<li ng-show = "a.address"> Address {{a.address}}</li>
</ul>
</div>
<script>
</script>
<p>ng-show didnt accept expressions.</p>
答案 1 :(得分:0)
只需删除true
和false
中的单引号。如果您在true
和false
上添加引号,则它们就是字符串。在这种情况下ng-show
正在检查变量是否已定义。在您的情况下,由于它具有字符串真/假值,因此ng-show正在考虑表达式,因此为真。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show="a.name"> Name {{a.name}} </li>
<li ng-show="a.id"> Id {{a.id}}</li>
<li ng-show="a.address"> Address {{a.address}}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name': false,
'id': true,
'address': false
};
});
</script>
<p>ng-show didnt accept expressions.</p>
</body>
</html>
&#13;
答案 2 :(得分:0)
1.4.8
显示支持值为布尔值而不是字符串布尔值。因此,您需要删除值周围的引号
$scope.a = {
'name' : false,
'id' : true,
'address' : false
};
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name' : false,
'id' : true,
'address' : false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show = "a.name"> Name {{a.name}} </li>
<li ng-show = "a.id"> Id {{a.id}}</li>
<li ng-show = "a.address"> Address {{a.address}}</li>
</ul>
</div>
但是如果您使用的是1.2.23
之类的较低版本,那么如果值为true或false,则angular将字符串值标识为布尔值
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.a = {
'name' : 'false',
'id' : 'true',
'address' : 'false'
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<ul>
<li ng-show = "a.name"> Name {{a.name}} </li>
<li ng-show = "a.id"> Id {{a.id}}</li>
<li ng-show = "a.address"> Address {{a.address}}</li>
</ul>
</div>