将数据从外部模型绑定到angularjs
binding data to angularjs from external model
我的应用程序中有指令和服务(在单独的文件中声明):
服务:(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
相关文章:
- AngularJS绑定没有'在没有填充父范围的情况下无法工作
- AngularJS绑定仅在更改后更新
- 如何防止 jQuery-UI 按钮集破坏 AngularJS 绑定
- AngularJS绑定模型以选择更新输入数字字段,最小值为最大值
- 如何在没有任何浏览器插件的情况下调试AngularJS绑定{{expression}}
- angularjs绑定赢得'除非我打GET电话,否则不会显示
- AngularJs绑定以进行选择
- AngularJS绑定到输入的回车键,如果输入是按钮,则提交
- 我怎样才能让 AngularJS 绑定使用花哨的框对话框
- AngularJS 绑定要选择的数据下拉列表,当另一个选择下拉列表的值发生更改时
- Angularjs 绑定 2 指令将模型范围限定为父控制器模型
- 使用 AngularJS 绑定图像标记
- AngularJS绑定变量超出范围并通知更新
- 如何使用 AngularJS 绑定后获取元素的字符串长度
- 多窗口使用AngularJS绑定相同的数据
- AngularJS绑定函数到多个元素
- AngularJS:绑定到所有对象属性
- Angularjs 绑定到 JSON 会将值设置为 undefined
- Angularjs 绑定在从 ng-click 调用时不起作用
- AngularJS绑定到嵌套模型属性