Timo.Klement
Timo.Klement

Reputation: 637

AngularJS won't update view

I'm just new to angularJS and have my first big problem. First I wanted to create a list and update it, but it doesn't work.

// index.html
<form ng-controller="ListCtrl">
    <div class="form-group">
        <input name="listname" ng-model="listname">
        <input type="button" ng-click="set()" value="add new list">
    </div>
</form>
<div ng-controller="ListCtrl">
    <ul>
        <li ng-repeat="list in lists">
            {{list.id}} - {{list.listname}}
        </li>
    </ul>
    {{output}}
</div>

The fun part is the resetForm(), there I reset the form but also will try to update the $scope.output. But that output never changes, no matter what I try to change.

// ListCtrl
var ListApp = angular.module('ListApp', []);

ListApp.controller('ListCtrl', function ($scope) {
// add new records to database
$scope.set = function() {
    $scope.createTableIfNotExists();
    $scope.insertSql = 'INSERT INTO Lists (listname) VALUES (?)';

    if ($scope.listname) {
        $scope.db.transaction(
            function (transaction) {
                transaction.executeSql($scope.insertSql, [$scope.listname], resetForm);
            }
        );
    }
};

function resetForm() {
    // clear the input field
    $scope.listname = "";
    $scope.listForm.$setPristine();
    $scope.output = 'Hello World';
    $scope.$apply();
}

Edit: When I try this with $apply the console shows me an error:

function resetForm() {
    $scope.$apply(function () {
        $scope.listname = "";
        $scope.listForm.$setPristine();
        $scope.output = 'Hello World';
    });
}

And the error is:

Uncaught TypeError: undefined is not a function 

The error points direct to the start of "$scope.$apply(function..."

Edit 2: When I add a new button in index.html and call a function with ng-click and in this function I just say

$scope.output = 'Hello World!';

Then my view updates. It will only not update when I use a callback to change the scope. Don't understand that. I thought everything is connected in angularJS, especially when I'm in the same controller.

Edit 3: Here is the plunker

Upvotes: 0

Views: 1325

Answers (1)

Danilo Valente
Danilo Valente

Reputation: 11352

Uncaught TypeError: undefined is not a function

That's because you called $scope.apply instead of $scope.$apply.

Try calling it with a callback function:

$scope.$apply(function () {
    $scope.listname = "";
    $scope.listForm.$setPristine();
    $scope.output = 'Hello World';
});

Upvotes: 1

Related Questions