请阅读控制器代码。 我无法打印每个披萨的价格。 我已经想到,即使我初始化了mainDish对象的价格和名称,它也不会在第一次运行代码时在网页上显示。 / * 我正在写这些额外的单词,因为stackoverflow不允许我发布这个,因为它认为代码需要更多细节... * /
<!DOCTYPE html>
<html ng-app="app">
<head>
<title>Tony's Pizza</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
</head>
<body ng-controller="menuController">
<div class="container">
<h1>Tony's Pizza</h1>
<h2>{{model.title}}</h2>
<div>
<label><input type="radio" name="category" ng-click="changeMainDish('Cheese Pizza')"/> Cheese Pizza</label>
</div>
<div>
<label><input type="radio" name="category" ng-click="changeMainDish('Pepperoni Pizza')"/> Pepperoni Pizza</label>
</div>
<div>
<label><input type="radio" name="category" ng-click="changeMainDish('Margherita Pizza')"/> Margherita Pizza</label>
</div>
<div>
<label><input type="radio" name="category" ng-click="changeMainDish('BBQ Chicken Pizza')"/> BBQ Chicken Pizza</label>
</div>
<div>
<label><input type="radio" name="category" ng-click="changeMainDish('Combo Pizza')"/> Combo Pizza</label>
</div>
<div>
<h3>Selected Item</h3>
<pre>{{model.mainDish.name}}</pre>
</div>
<div>
<h3>Special Instuctions</h3>
<textarea class="form-control" ng-model="model.specialInstructions"></textarea>
</div>
<div>
<h3>Order Summary</h3>
<pre> {{ model.mainDish.name }} {{ model.mainDish.price }} - {{ model.specialInstructions }} </pre></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="./app/app.js"></script>
<script src="./app/menuController.js"></script>
</body>
</html>
脚本&GT;
var app = angular.module('app', []);
app.controller('menuController', [
'$scope',
function($scope){
$scope.model={title:'Our Menu',
mainDish:[{name:''},{price:''}]};
$scope.$watch('model.mainDish.name',function(newValue,oldValue){
if(newValue==='BBQ Chicken Pizza'){
alert('You have selected BBQ Chicken Pizza');
model.mainDish.price= 10;
}
if(newValue==='Cheese Pizza'){
model.mainDish.price= 15;
}
if(newValue==='Pepperoni Pizza'){
model.mainDish.price= 20;
}
if(newValue==='Margherita Pizza'){
model.mainDish.price= 30;
}
if(newValue==='Combo Pizza'){
model.mainDish.price= 40;
}
});
$scope.changeMainDish = function (item) {
$scope.model.mainDish.name = item;
}
}
]);</script>
答案 0 :(得分:0)
出现问题的原因是您声明mainDish的方式。在您的代码中,mainDish是一个数组,但您可以像访问它一样访问它。您不能以他们想要的方式对嵌套对象使用$ watch。最佳解决方案是关注the answer given on this question,并使用ng-change
和ng-model
。