Martin Fric Martin Fric - 1 month ago 11
AngularJS Question

AngularJS , pushing empty element

Im quite new with angular. What am i freaky about is that following code is showing empty buttons (edit/delete) even if it looks empty (on start) :

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">

<h2>todo</h2>

<form ng-submit="todoAdd(item)">
<input type="text" ng-model="todoInput" size="50" placeholder="Add New">
<input type="submit" value="Add New">
</form>

<br>

<div ng-repeat="x in todoList">
<span ng-bind="x.todoText"></span><button id="#edit" ng-click="edit(item)">edit</button><button ng-click="remove(item)">delete</button>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('todoCtrl', function($scope) {
$scope.todoList = [{}];

$scope.todoAdd = function(item) {
$scope.todoList.push({todoText:$scope.todoInput);
$scope.todoInput = "";
};

$scope.remove = function(item) {
var index = $scope.todoList.indexOf(item);
$scope.todoList.splice(index, 1);
};
$scope.edit = function(item) {
//function
};
});
</script>

</body>
</html>


And also can somebody to help me after clicking on edit to push todoText to input and change caption of addnew to save? and afterthen change it to addNew again?

Thank you very much

Answer

Replace line

$scope.todoList = [{}];

to

$scope.todoList = [];

Then, it wouldn't show you empty line.

//Full code.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body ng-app="myApp" ng-controller="todoCtrl">

<h2>todo</h2>

<form>
    <input type="text" ng-model="todoInput" size="50" placeholder="Add New">
    <input type="button" value="{{actionName}}" ng-click="todoAdd()" />
</form>

<br>

<div ng-repeat="x in todoList">
   <span>{{x.todoText}}</span><button id="#edit" ng-click="edit(x)">edit</button><button ng-click="remove(item)">delete</button>
</div>

<script>
var app = angular.module('myApp', []); 
app.controller('todoCtrl', function($scope) {
    $scope.todoList = [];
    $scope.actionName = 'Add';

    $scope.todoAdd = function() {
     if($scope.actionName === 'Add'){
        $scope.todoList.push({todoText:$scope.todoInput});
        $scope.todoInput = "";
     } else {
        var index = $scope.todoList.indexOf($scope.temp);
        console.log('index: ' + index);
        $scope.todoList.splice(index, 1, {todoText:$scope.todoInput});
        $scope.actionName = 'Add';
     }
    };

    $scope.remove = function(item) {
        var index = $scope.todoList.indexOf(item);
        $scope.todoList.splice(index, 1);
    };
    $scope.edit = function(item) {
        $scope.todoInput=item.todoText;
        $scope.temp = item;
        $scope.actionName = 'Save';
    };
});
</script>

</body>
</html>
Comments