为什么我的棱角花括号不起作用?

时间:2017-03-19 19:55:45

标签: angularjs controller curly-braces

我的花括号显示为花括号,我没有弄错,我做了一切......当我使用控制器来操作输入框时,它可以工作。但是当我将文本汇总到浏览器的输入框中时,它什么也没做。

这是我创建模块的地方:

'use strict';
 var foodApp=angular.module('foodApp', []);

这是我的HTML:

<script src="/lib/angular/angular.js"></script>

<!DOCTYPE html>

<html lang="en-us" >
<head>
<meta charset="utf-8">
<title>Food App</title>
</head>

<body>
<div  ng-controller="foodController" ng-app="foodApp">
    <input type="text" ng-model="foods"/>
    <input type="submit" value="Healthy Lunch?" />
    <br />
    <br />

    <h4>{{outcome}}</h4>

        {{foods}}
</div>
<script src="/js/food.js"></script>
<script src="/js/controllers/foodController.js"></script>
</body>
</html>

这是我的控制器页面:

foodApp.controller('foodController', function($scope)
{

var foods = $scope.foods;
$scope.outcome=foods;
var foodsArray=foods.split(',');

if(foodsArray.length<=4)
$scope.outcome="Bon Appetit!";

else if(foodsArray.length<=7)
$scope.outcome="Pig!";

else
 $scope.outcome="One at a time, your scale is going to shout!!";
});

1 个答案:

答案 0 :(得分:0)

问题实际上在您的控制器中。控制器构建时,控制器中的代码只执行一次。因此变量foods未定义(因为$scope.foods也未定义)。稍后几行,您尝试运行foods.split(..)但由于它未定义,它会抛出异常并且应用程序失败。这在浏览器的开发人员控制台中显示为错误。

要修复它,您需要完全重构控制器代码。

foodApp.controller('foodController', function($scope)
{
    $scope.handleFoodChange = function() {

        $scope.outcome = $scope.foods;
        if($scope.foods){
            var foodsArray = $scope.foods.split(',');

            if(foodsArray.length<=4)
                $scope.outcome = "Bon Appetit!";
            else if(foodsArray.length<=7)
                $scope.outcome = "Pig!";
            else
                $scope.outcome = "One at a time, your scale is going to shout!!";
        }
    }
});

并且在您的视图中,您应该将输入更改为:

<input type="text" ng-model="foods" ng-change="handleFoodChange()" />

这应该使您的应用程序按预期工作。现在,无论何时在输入字段中进行更改,都会调用函数handleFoodChange,并处理为$scope.outcome变量设置值的逻辑。

Here's a Plunker showing it working