angularjs跨window controller互操作的方法
项目中有跨window的相互交互的场景,不适合用模态窗口做。通过指令很容易满足该需求。
具体思路:在window1的一个element上使用jquery的事件绑定,在指令里回调scope的属性或方法。
window2就在需要回调的方法里去触发window1的element的事件。
具体实现代码如下:
define(function(require){ var moduleName = 'ng.ext.trigger-bridge'; return { init: function(){ window.console.log('Begin init module ' + moduleName); if(angular.isModuleExists && angular.isModuleExists(moduleName)){ window.console.log('Module already exists!' + moduleName); return; } var md = angular.module(moduleName, []); md.factory('extTriggerBridgeService', function(){ return { trigger: function(el, type, field, data){ el.trigger(type || 'scopeChange', [field, data]); }, triggerInWindow: function(win, elementId, type, field, data){ // cross window, use jquery not jqLite in global if(win && win.$){ var elDom = win.document.getElementById(elementId); win.$(elDom).trigger(type || 'scopeChange', [field, data]); } } }; }); // *** *** *** *** *** *** *** *** *** *** // *** *** *** *** *** *** *** *** *** *** md.directive('extTriggerBridge', ['$parse', function($parse){ 'use strict'; return { restrict: 'A', // begin link *** link: function(scope, el, attrs, ctrl){ var opts = scope.$eval(attrs.extTriggerBridge) || {}; console.log('Init extTriggerBridge - ' + JSON.stringify(opts)); el.bind(opts.eventType || 'scopeChange', function(e, field, data){ console.log('Trigger : ' + JSON.stringify(opts) + ' - ' + field + ' - ' + JSON.stringify(data)); if(opts.setData){ // set data if(data){ var getter = $parse(field); var setter = getter.assign; var oldVal = getter(scope) || {}; angular.extend(oldVal, data); scope.$apply(function(){ setter(scope, oldVal); }); } }else if(opts.callFn){ // call function var fnTarget = $parse(field)(scope); if(!fnTarget || !angular.isFunction(fnTarget)){ console.log('No function defined : ' + field); }else{ scope.$apply(function(){ fnTarget(data); }); } }else{ // emit event var eventName = field; scope.$apply(function(){ scope.$emit(eventName, data); }); } }); } // end link *** }; // end link }]); // end directive } // end init }; });
相关推荐
xingdongfang 2019-11-10
zhenghao 2014-05-30
youyouzouzou 2014-05-30
zbwroom 2014-05-30
zbwroom 2014-05-29
鸟菜小端前 2018-09-12
lizean 2015-03-10
zbwroom 2015-04-10
Oranq 2015-08-29
CrazyDogWang 2016-01-06
lizean 2016-04-30
小新正在敲代码 2016-04-14
CrazyDogWang 2016-11-30
lizean 2016-12-19
princejingyun 2016-12-14
youyouzouzou 2017-02-24
youyouzouzou 2017-05-30
Oranq 2017-05-30
Oranq 2017-09-09