Search code examples
angularjscontrollercurly-braces

Why are my angular curly braces not working?


My curly braces are showing up as curly braces, I don't get what's wrong, I did everything...when I use the controller to manipulate the input box, it works. But when I sumbit text into the input box on my browser, it doesn't do anything..

This is where I create my module:

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

This is my 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>

This is my controller page:

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!!";
});

Solution

  • The problem is in fact in your controller. The code you have in your controller is only executed once, when the controller is constructed. As such the variable foods is undefined (since $scope.foods is also undefined). A couple of lines later, you try to run foods.split(..) but since it's undefined, it throws an exception and the application fails. This is shown as an error in the developer console of your browser.

    To fix it you need to completely refactor your controller code.

    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!!";
            }
        }
    });
    

    and in your view you should change your input to this:

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

    That should make your application work as expected. Now, whenever you make a change in the input field, the function handleFoodChange is called, and it handles the logic that sets a value for the $scope.outcome variable.

    Here's a Plunker showing it working