iWillBeMaster iWillBeMaster - 7 months ago 22
HTML Question

AngularJS does not repeat array

So the problem is that ng-repeat in list.html is not showing anything(or is it even getting anything?). I would also like to know if that if-statement in my $scope.save function is stupid way to do that or no (i mean changing checkbox boolean to "yes" or "no" string).

index.html

<!DOCTYPE html>
<html ng-app="app">
<body ng-controller="mainController">
<div ng-view></div>
</body>
</html>


form.html

<form role="form">
<label>Nimi:</label>
<input ng-model="newcontact.name" type="text" class="form-control">
<label>Email:</label>
<input ng-model="newcontact.email" type="text" class="form-control">
<label>Ruokavalinta:</label>
<select ng-model="newcontact.ruoka" class="form-control">
<option>Kala</option>
<option>Liha</option>
<option>Kasvis</option>
</select>
<label><input ng-model="newcontact.sauna" type="checkbox"> Osallistun saunailtaan</label>
<button ng-click="save()" class="btn btn-default">Submit</button>
</form>


list.html

<table>
<tbody>
<tr ng-repeat="object in list">
<td>{{object.name}}</td>
<td>{{object.email}}</td>
<td>{{object.ruoka}}</td>
<td>{{object.sauna}}</td>
</tr>
</tbody>
</table>


app.js

var app = angular.module("app", ["ngRoute"]);

app.config(["$routeProvider", "$locationProvider",
function($routeProvider, $locationProvider){
var app = angular.module("app", ["ngRoute"]);

app.config(["$routeProvider", "$locationProvider",
function($routeProvider, $locationProvider){
$routeProvider
.when
("/list", {templateUrl: "harjoitus10/templates/list.html",
controller: "mainController"})
.when
("/form", {templateUrl: "harjoitus10/templates/form.html",
controller: "mainController"})
.otherwise({redirectTo: "/"});
$locationProvider.html5Mode({enabled:true, requireBase:false});
}]);

app.service("dataservice", function(){
var list = [{}];

this.save = function(newcontact){
list.push(newcontact);
};
this.returnList = function(){
return list;
};
});

app.controller("mainController", function($scope, dataservice){

$scope.list = dataservice.returnList;

$scope.save = function(){
if($scope.newcontact.sauna){
$scope.newcontact.sauna = "joo";
}else{
$scope.newcontact.sauna = "ei";
}
dataservice.save($scope.newcontact);
$scope.newcontact = {};
};
});

Answer

returnList is a method of dataservice, not a property of type array, so your mainController should call it with brackets:

app.controller("mainController", function($scope, dataservice){

    $scope.list = dataservice.returnList();

    $scope.save = function(){
        if($scope.newcontact.sauna){
            $scope.newcontact.sauna = "joo";
        }else{
            $scope.newcontact.sauna = "ei";
        }
        dataservice.save($scope.newcontact);
        $scope.newcontact = {};
    };
});
Comments