经过相当多的研究,并参考以下问题,这是 Scope 的扩展,它允许双向绑定(本质上,它是 Angular 代码,仅修改为在外部工作nodeLinkFn
):
angular.module('scopeBindExtention', [])
.run( [ '$rootScope', '$parse', function( $rootScope, $parse ) {
var extended = angular.extend( $rootScope, {} );
extended.$bindTwoWay = function( scopeName, parentName ) {
var scope = this,
parentScope = scope.$parent;
lastValue,
parentGet,
parentSet,
compare;
parentGet = $parse(parentName);
if (parentGet.literal) {
compare = angular.equals;
} else {
compare = function(a,b) { return a === b; };
}
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
throw new Error( "Expression '" + parentName + "' is non-assignable!" );
/*
throw $compileMinErr('nonassign',
"Expression '{0}' is non-assignable!",
parentName);
*/
};
lastValue = scope[scopeName] = parentGet(parentScope);
var unwatch = parentScope.$watch($parse(parentName, function parentValueWatch(parentValue) {
if (!compare(parentValue, scope[scopeName])) {
// we are out of sync and need to copy
if (!compare(parentValue, lastValue)) {
// parent changed and it has precedence
scope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, parentValue = scope[scopeName]);
}
}
return lastValue = parentValue;
}), null, parentGet.literal);
scope.$on('$destroy', unwatch);
}
}]);
客户只需致电:
scope.$bindTwoWay('childModelName', 'parentModelName');