Angularjs service callback to update scope of controller

后端 未结 4 757
[愿得一人]
[愿得一人] 2021-01-31 18:49

A service with a 3rd party library callback function:

mbAppModule.service(\'aService\', function ($http) {
    this.data={\"somedata\":0};
    var m3rdPartLib=\         


        
相关标签:
4条回答
  • 2021-01-31 19:12

    If you´re using scope in your service then it is a good indicator that you´re breaking SRP cause your service should only retrieve data to your controller. My suggestion is that you could do something like this.

    mbAppModule.service('aService', ["$http", "$rootScope", function ($http, $rootScope) {
      this.data = {
        "somedata": 0
      };
      var m3rdPartLib = "init"; // init    
      this.GetPartLib = function () { 
        return m3rdPartLib;
      }
    }]);
    
    mbAppModule.controller({
      MController: function ($scope, $http, mService) {
      this.GetPartLib = function (){ 
        mService.on('timeupdate', function() {
         this.data.somedata=1;
        });
      }
    });
    
    0 讨论(0)
  • 2021-01-31 19:23

    I needed to update an input field from a service because it had listeners and what not that changed data randomly and dynamically.

    This could be used to call scope functions in the controller as well:

    //scope will be set to current scope of a controller
    //which has an ng-view containing this element    
    var scope = angular.element('#input-element').scope();
    //wrap changes in an apply call to make sure view and model are consistent
    scope.$apply(function() {
        scope.object.data = value;
    });
    

    Thanks to this post: How do I access the $scope variable in browser's console using AngularJS?

    0 讨论(0)
  • 2021-01-31 19:31

    You can take a dependency on $rootScope and call apply in your service.

    mbAppModule.service('aService', ["$http", "$rootScope", function ($http, $rootScope) {
        this.data = {
            "somedata": 0
        };
        var m3rdPartLib = "init"; // init    
        m3rdPartLib.on('timeupdate', function () {
            $rootScope.$apply(function(){
                this.data.somedata = 1;
            });
        });
    }]);
    
    0 讨论(0)
  • 2021-01-31 19:33

    Use $scope.$watch function. Look at my jsfiddle. I haven't your library, so I only simulate it - the value change from 0 to 1 after 5 seconds.

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