AngularJS update view with service/model changes using $q promises -



AngularJS update view with service/model changes using $q promises -

i'm trying load info service , update view using $q, it's not working. works if set http phone call within controller, i'd prefer part of service.

any help? also, there improve way instead of promises?

demo , code below.

---------- fiddle demo link ----------

view

<div ng-init="getdata()"> <div ng-repeat="item in list">{{item.name}}</div> </div>

controller

.controller('ctrl', ['$scope', 'dataservice', '$q', function ($scope, dataservice, $q) { $scope.list = dataservice.datalist; var loaddata = function () { dataservice.fakehttpgetdata(); }; var setdatatoscope = function () { $scope.list = dataservice.datalist; }; $scope.getdata = function () { var defer = $q.defer(); defer.promise.then(setdatatoscope()); defer.resolve(loaddata()); }; }])

service

.factory('dataservice', ['$timeout', function ($timeout) { // view displays list @ load this.datalist = [{'name': 'alpha'}, {'name': 'bravo'}]; this.fakehttpgetdata = function () { $timeout(function () { // view should display list after 2 seconds this.datalist = [{'name': 'charlie'}, {'name': 'delta'}, {'name': 'echo'}]; }, 2000); }; homecoming this; }]);

no need nginit or $q. how should it.

you should not expose dataservice.list controller. should private dataservice, contain of logic determine whether send controller existing list or update list , send it.

angular.module('app', []) .controller('ctrl', ['$scope', 'dataservice', function ($scope, dataservice) { loaddata(); function loaddata() { dataservice.fakehttpgetdata().then(function (result) { $scope.list = result; }); } }]) .factory('dataservice', ['$timeout', function ($timeout) { var datalist = [ { 'name': 'alpha' }, { 'name': 'bravo' } ]; this.fakehttpgetdata = function () { homecoming $timeout(function () { // logic here determine list should (what combination of new info , existing list). datalist = [ { 'name': 'charlie' }, { 'name': 'delta' }, { 'name': 'echo' } ]; homecoming datalist; }, 2000); }; homecoming this; }]);

angularjs promise angular-promise

Comments

Popular posts from this blog

model view controller - MVC Rails Planning -

ruby on rails - Devise Logout Error in RoR -

html - Submenu setup with jquery and effect 'fold' -