2

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?

1 Answer 1

0

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

3
  • It looks like you've now polluted your native model with angular-specific cruft -- you shouldn't have to do this Commented Jun 16, 2013 at 17:05
  • You right - this is not best solution. I think if we have some kind of event based system, then we can emit model modification event, and call angular-specific code outside of model, in event handler. for getting data from angular to model i think we i can create some kind of native "service", that provides access to angular service fields and methods, so we call all angular-specific staff in that additional native layer, and not in the model. i'm on the right way? Commented Jun 26, 2013 at 6:17
  • angular should be using and delegating to your Model objects, not the other way around. One way to make your model objects available wherever you need them in angular, is to wrap them into angular services. Then you can inject them into your angular code. Commented Jun 26, 2013 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.