1
votes

I am trying to build a search function using Angular and a RESTful web service. I am a complete newbie to Angular, so bear with me.

I have the event handling and communication with the web service wired and working. Problem is that my view never gets updated when I assign the results of my search query to the $scope in the $http success callback.

However, I do get data back in the $http callback and if I try to update my model in this callback using static data, this does not show up either.

I am at a complete loss whether I am pushing my result records to a wrong $scope or what is going on. $scope.$apply() does not work because a model update is already in progress. I also tried different versions of Angular, to no avail. Using $resource instead of $http did nothing to solve the problem.

Anyone got an idea? Thanks in advance

I also set up a JSFiddle with a bit more diagnostics in the controller

My HTML:

    <div ng-app="myApp">
        <div ng-controller="SearchCtrl">
            <div ng-repeat="result in results" class="result">
                <div class="board">
                    <div class="name">{{result.board}}</div>
                    <div class="posts">{{result.posts}}</div>
                    <div class="clear"></div>
                </div>
                <div class="clear"></div>
            </div>
        </div>
        <div>
        <form ng-submit="doSearch()" ng-controller="SearchCtrl" name="search" id="search">
            <input type="text" value="" ng-model="searchTerm"   name="q" id="searchterm"></input>
            <button class="search" id="searchbtn" type="submit">Search</button>
        </form>
        </div>
    </div>
    

my controller:

myApp.controller('SearchCtrl', function ($scope, $http) {
    $scope.results = [];
    $scope.doSearch = function () {
        data = 'json=' + encodeURIComponent(angular.toJson([{
            board: "one", posts: 435
        }, {
            board: "two", posts: 123
        }]));
        $http.post('/echo/json/', data, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            }
        }).success(function (data) {
            for (var i in data) {
               $scope.results.push(data[i]);
            }
        });
    };
})
1

1 Answers

3
votes

You are creating two instances of the controller. The form and the list must be inside the same <div ng-controller="SearchCtrl"> element. <form> should not have its own SearchCtrl

See problem fixed here: http://jsfiddle.net/EeUrY/68/.