Kulvis
Kulvis

Reputation: 655

UI is not updated after firering a ng-click event on my AngularJS controller

I've bound a button with a ng-click event that fires a function on my controller. This again gets some data using $http and this works just fine. But when updateing my model in the success-callback the UI doesnt get updated. I've tried using $scope.$apply and $scope.safeApply without luck. Nothing happens in the UI. Data is returned from service. See code below.

SearchController:

'use strict';

searchApp.controller('SearchController',    
function SearchController($scope, searchData) {

    $scope.query = '';
    $scope.isLoading = false;
    $scope.result = null;

    $scope.doSearch = function () {
        $scope.isLoading = true;

        searchData.getSearchResult($scope.query, function (result) {
            $scope.safeApply(function() {
                $scope.result = result;
                console.log($scope.result);
            });
        });
    };

    $scope.safeApply = function (fn) {
        var phase = this.$root.$$phase;
        if (phase == '$apply' || phase == '$digest') {
            if (fn && (typeof (fn) === 'function')) {
                fn();
            }
        } else {
            this.$apply(fn);
        }
    };
}
);

HTML markup:

<div class="search-result" ng-controller="SearchController">

<input type="text" value="Enter query..." ng-model="query" />
    <input type="button" value="Search" ng-click="doSearch()" />
        <div ng-show="isLoading">
            Searching....
        </div>

        <h2>{{ result.SearchGroups }}</h2>

        <div class="result-box" ng-repeat="group in result.SearchGroups">
            <div class="head">
                <h2>{{ group.Name }}</h2>
                <!--<span class="seeAll">Se alle (13)</span>-->
            </div>
            <div class="body">

            </div>
        </div>

    </div>

Upvotes: 1

Views: 1447

Answers (1)

Brian Genisio
Brian Genisio

Reputation: 48137

Forget about the $safeApply stuff. As long as searchData.getSearchResult is using $http to make its request, you should never need to call $apply or $safeApply. These are really only necessary when getting events from non-angular sources. In other words, it is rare, in a controller, that you need to dall $apply. If you find yourself doing it, you should know why.

So, assuming your result is coming through, assigning it to $scope.result should just work. Some questions to ask:

  1. Is your console.log printing out? Are you really receiving your data?
  2. Does result have a property called SearchGroups? Case sensitivity matters
  3. If you dump the result {{result}} does it show anything?

If none of these questions yield a result, can you share your searchData.getSearchResult service function?

Upvotes: 2

Related Questions