自定义指令中作用域对象内的嵌套对象

时间:2016-01-20 12:14:56

标签: javascript angularjs angularjs-directive

为什么我的范围对象中的嵌套对象中没有绑定,如下所示:

app.directive('myDirective', function() {
    return {
        scope: {
            dropdown: {
                option: '=selectedOption' //not working
            } 
        }
    }
})

我收到错误:

  

a.match不是函数

这里是working plunker.

2 个答案:

答案 0 :(得分:1)

“为什么”的答案是“因为这不是它的工作方式”。

解析指令范围的AngularJS源代码位于:https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L829

  function parseIsolateBindings(scope, directiveName, isController) {
    var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;

    var bindings = {};

    forEach(scope, function(definition, scopeName) {
      var match = definition.match(LOCAL_REGEXP);

      if (!match) {
        throw $compileMinErr('iscp',
            "Invalid {3} for directive '{0}'." +
            " Definition: {... {1}: '{2}' ...}",
            directiveName, scopeName, definition,
            (isController ? "controller bindings definition" :
            "isolate scope definition"));
      }

      bindings[scopeName] = {
        mode: match[1][0],
        collection: match[2] === '*',
        optional: match[3] === '?',
        attrName: match[4] || scopeName
      };
    });

    return bindings;
  }

正如您所看到的,它只通过scope对象属性进行单次传递,并且不会递归地下降到对象属性中。

答案 1 :(得分:0)

不确定这是否有效:

scope: {
    "dropdown.option": "=selectedOption"
}

但是,作为一种解决方法,您可以这样写:

app.directive('myDirective', function() {
    return {
        scope: {
            dropdownOption: "=selectedOption"
        },
        controller: ["$scope", function($scope) {
            $scope.dropdown = $scope.dropdown || {};

            $scope.$watch('dropdownOption', function(newValue) {
                $scope.dropdown.option = newValue;
            });


            $scope.$watch('dropdown.option', function(newValue) {
                $scope.dropdownOption = newValue;
            });
        }]
    }
})