将数据从外部模型绑定到angularjs

binding data to angularjs from external model

本文关键字:angularjs 绑定 模型 数据 从外部      更新时间:2023-09-26

我的应用程序中有指令和服务(在单独的文件中声明):

服务:

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

指令:

(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;
                });
            }
        }
    });
})();

在另一个单独的文件中,我有native model:

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

我如何绑定(两种方式)我的原生this.fld字段值在我的AngularJS服务?

解决方案是使用以下代码:

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

我认为在$rootScope上使用$digest是坏主意,所以我们可以使用

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

获取所需的作用域并为其调用$digest