javascript - AngularJS: The "best" way to bind a Factory variable to a $scope or a directive? -
i'm working on new angularjs project, , encountered problem annoys me more should...
i have angular service containing data need access multiple views , controllers, , updated service receiving continuous data server, via socketio.
something :
angular.module('foo', [])  .factory('datacontainer', function(){       var data = [];     var o = {};     o.all = function() {         return data;     };     o.add = function(item){         data.push(item);     };     return o;  })  .factory('datareceiver', function(datacontainer){     var o = {}     o.init = function(){          socket = io.connect()          .on('data', function(item){               datacontainer.add(item);          };     };    return o; })  .directive('datalist', function(datacontainer) {     return {         restrict: 'e',         template: '<ul><li ng-repeat="item in data">{{item}}</li></ul>',         replace: true,         link: function(scope) {             scope.data = datacontainer.all();         }     }; });   problem "datalist" update when datacontainer.add() call parent's controller, not when datacontainer.data updated datareceiver service (as $scope not update).
i tried many things, including things :
$scope.data = datacontainer; ..... ng-repeat="item in data.all() track $index"   thinking solve problem. didn't.
i'm considering using $rootscope, or $watch combined $scope.apply() pass , update data, sounds pretty heavy, , i'm not sure it's proper way go...
what doing wrong ? proper way bind service variable controller $scope or directive ? !
try this
.factory('datareceiver', function(datacontainer, $rootscope){     var o = {}     o.init = function(){          socket = io.connect()          .on('data', function(item){               datacontainer.add(item);               $rootscope.$apply()          };     };    return o; })      
Comments
Post a Comment