Angularjs手册双向绑定

时间:2013-11-02 20:59:48

标签: javascript angularjs

描述我的问题的最佳方式是演示。这就是我希望使用我的指令的方式:

<my-directive my-attr="{'property': obj}"></my-directive>

其中'obj'是我希望双向绑定的范围上的对象。问题是我还需要获取对象'obj'的名称。

我提出的部分解决方案是将对象的名称('obj')作为字符串传递,并使用$ parse来获取对象。但是当这不会影响$ parent范围时,使用范围'='会以相同的方式。如何手动编写双向绑定,以便更改我的作用域上的对象将更改父作用域上的对象?

3 个答案:

答案 0 :(得分:1)

经过相当多的研究,并参考following issue,这里是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);    
    }

}]);

客户应该致电:

范围。$ bindTwoWay('childModelName','parentModelName');

答案 1 :(得分:0)

可以使用此对象语法:

scope[ attrs.myAttr] 

访问父范围属性,因为您没有在指令

中使用隔离范围

答案 2 :(得分:-1)

我设法解决了我的问题。我的解决方案(在coffeescript中):

$scope.$watch name, (val) ->
  scope = $scope.$parent
  # look up the scopes until the real object is found
  while scope isnt null
    if not scope.hasOwnProperty(name)
      scope = scope.$parent
    else
      expressions[name].assign(scope, val)
      scope = null

这将检查作用域链并找到定义该对象的作用域并在那里进行修改。我相信这与使用范围几乎完全相同:在指令定义中使用'='。