Search code examples
javascriptangularjsangularjs-service

binding data to angularjs from external model


I've got directive and service in my app (declared in separate files):

Service:

(function(){
    angular.module('core', [])
    .factory('api', function() {
        return {
            serviceField: 100
        };
    })
})();

Directive:

(function(){
    angular.module('ui', ['core'])
    .directive('apiFieldWatcher', function (api) {
        return {
            restrict: 'E',
            replace: true,
            scope: true,
            template: '<div>+{{apiField}}+</div>',
            controller: function($scope) {
                $scope.apiField = 0;
            },
            link: function (scope) {
                scope.$watch(function(){return api.serviceField}, function(apiFld){
                    scope.apiField = apiFld;
                });
            }
        }
    });
})();

And in another separate file I have native model:

function Model() { this.fld = 0; }
Model.prototype.setFld = function(a) { this.fld = a; }
Model.prototype.getFld = function() { return this.fld; }

How can I bind (two way) my native this.fld field to value in my AngularJS service?


Solution

  • The solution is in using this code:

    Model.prototype.setFld = function(a) {
      this.fld = a;
      injector.invoke(['$rootScope', 'api', function($rootScope, api){
        api.setField(a);
        $rootScope.$digest();
      }]);
    };
    
    Model.prototype.getFldFromApi = function() {
      var self = this;
      injector.invoke(['api', function(api){
        self.fld = api.getField();
      }]);
    };
    

    http://plnkr.co/edit/nitAVuOtzGsdJ49H4uyl

    i think it's bad idea to use $digest on $rootScope, so we can maybe use

    var scope = angular.element( elementObject ).scope();
    

    to get needed scope and call $digest for it