I am trying to make a Menu (with first, second and dessert) and I would like to introduce a input
to introduce a new dish in array
which I have created (to show it with ng-repeat
).
It seems that it does not fit into the functions that I create in the controller and it does nothing for me. It doesn't show me any error...
I'm running out of ideas. She left you the HTML code and the Angular.js code.
HTML code
<!DOCTYPE html>
<html>
<head>
<title>Angular JS</title>
</head>
<!-- Angular JS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MenuController">
<ul>
<h1>Menu</h1>
<h2>Primer Plato</h2>
<li ng-repeat="x in menu.primero">
{{ x }}
</li>
<input type="text" ng-model="cambiarPrimero" ng-keypress="MenuController.keyPressOnForm($event)" />
<h2>Segundo Plato</h2>
<li ng-repeat="x in menu.segundo">
{{ x }}
</li>
<h2>Postre</h2>
<li ng-repeat="x in menu.postre">
{{ x }}
</li>
</ul>
</div>
<script type="text/javascript" src="app.js"></script>
</body>
</html>
AngularJS code (store it in the root as app.js)
var app = angular.module('myApp', []);
app.controller("MenuController", function ($scope) {
$scope.menu= {
primero: ['sopa', 'paella','calamares'],
segundo: ['carne','pescado','tortilla'],
postre: ['fruta','yogur']
};
var keyPressOnForm = function(event) {
if (event.keyCode === 13) { //la key 13 es el enter
function updatePlato(){
$scope.menu.primero.push($scope.cambiarPrimero.text);
}
updatePlato();
}
}
});
Every idea is good.
You could try making the following modifications, in your html:
ng-keypress="keyPressOnForm($event)
In your controller:
$scope.keyPressOnForm = function(event) { if (event.keyCode === 13) { //la key 13 es el enter function updatePlato(){ $scope.menu.primero.push($scope.cambiarPrimero); } updatePlato(); } }
By using the $scope.keyPressOnForm you are scoping the function inside your controller.