AngularJS - Using a Service as a Model, ng-repeat not updating

后端 未结 2 1277
失恋的感觉
失恋的感觉 2020-12-13 11:00

I\'m creating an ajax search page which will consist of a search input box, series of filter drop-downs and then a UL where the results are displayed.

As the filters

相关标签:
2条回答
  • 2020-12-13 11:47

    In your HTML, you need to reference a property defined on your controller's $scope. One way to do that is to bind $scope.searchService.results to searchService.results once in your controller:

    $scope.searchService.results = searchService.results;
    

    Now this line will work:

    <li data-ng-repeat="item in searchService.results">
    

    In your service, use angular.copy() rather than assigning a new array reference to results, otherwise your controller's $scope will lose its data-binding:

    var new_results = [{ 'title': 'title 3' }, 
                       { 'title': 'title 4' }];
    angular.copy(new_results, results);
    

    Fiddle. In the fiddle, I commented out the initial call to find(), so you can see an update happen when you type something into the search box.

    0 讨论(0)
  • 2020-12-13 11:49

    The problem is that you're never updating your results within your scope. There are many approaches to do this, but based on your current code, you could first modify your find function to return the results:

    function find(term) {
        $http.get('/json/search').success(function(data) {
                var results = data.results;
    
        });
        //also notice that you're not using the variable 'term' 
        //to perform a query in your webservice
        return results;
    }
    

    You're using a module pattern in your 'public API' so your searchService returns the find function and an array of results, but you'd want to make the function find to be the responsible for actually returning the results.

    Setting that aside, whenever you call doSearch() in your scope, you'd want to update the current results for those returned by your searchService

    $scope.doSearch = function(){
        $scope.searchService.results = searchService.find($scope.search_term);
    };
    

    I updated your jsfiddle with my ideas, is not functional but i added some commments and logs to help you debug this issue. http://jsfiddle.net/XTQSu/3/

    0 讨论(0)
提交回复
热议问题