AngularJS: 使隔离作用域指令模板绑定到父作用域

AngularJS: Make isolate scope directive template bind to parent scope

我已经在 Angular 的 isolate scope 上挣扎了超过 24 小时。这是我的场景:我有一个 ng-repeat 遍历对象数组,我想使用自定义指令从中生成 <select><input> 基于 field_type 属性 当前正在迭代的对象。这意味着我必须在指令的 post-link 函数中生成模板和 $compile,因为我无法访问模板函数中的迭代对象。

除了生成的模板实际绑定到外部范围内的控制器 (vm) 之外,一切都按预期工作。我认为我的方法(将其添加到模板字符串中:ng-model="vm.prodAttribs.' + attr.attribute_code +'")可能是错误的,希望能指出正确的方向。谢谢!

参见下面的示例代码:

指令:

directives.directive('productAttributeWrapper', ['$compile',  function($compile){
    //this directive exists solely to provide 'productAttribute' directive access to the parent scope
    return {
        restrict: 'A',
        scope: false,
        controller: function($scope, $element, $attrs){
            this.compile = function (element) {
                $compile(element)($scope);
                console.log('$scope.prodAttribs in directive: ', $scope.prodAttribs);
            };
        }
    }
}]);

directives.directive('productAttribute', ['$compile',  function($compile){
    return {
        restrict: 'A',
        require: '^productAttributeWrapper', //use the wrapper's controller
        scope: {
            attribModel: '=',
            prodAttribute: '=productAttribute', //binding to the model being iterated by ng-repeat
        },
        link: function(scope, element, attrs, ctrl){
            var template = '';
            var attr = scope.prodAttribute;
            if(!attr) return;

            switch(attr.attribute_field_type.toLowerCase()){
                case 'textfield':
                    template = 
                        '<input type="text" id="'+attr.attribute_code+'" ng-model="vm.prodAttribs.' + attr.attribute_code +'">';
                    break;
                case 'dropdown':
                    template = [
                        '<select class="cvl" id="'+attr.attribute_code+'" ng-model="vm.prodAttribs.' + attr.attribute_code +'">',
                            '#cvl_option_values',
                        '\n</select>'
                    ].join('');
                    var options = '\n<option value="">Select One</option>';
                    for(var i=0; i<attr.cvl_option_values.length; i++) {
                        var optionVal = attr.cvl_option_values[i].value;
                        options += '\n<option value="'+optionVal+'">' + attr.cvl_option_values[i].value + '</option>';
                    }
                    template = template.replace('#cvl_option_values', options);
                    break;
            }
            element.html(template);
            ctrl.compile(element.html());  //try to bind template to outer scope
        }
    }
}]);

html:

<div ng-controller="ProductController as vm">
    <div product-attribute="attrib" ng-repeat="attrib in vm.all_attribs"></div>
</div>

控制器:

app.controller('ProductDetailsController', function(){
    var vm = this;
    //also added the property to $scope to see if i could access it there
    $scope.prodAttribs = vm.prodAttribs = {
            name: '',
            description: '',
            price: [0.0],
            condition: null
    }
    vm.all_attributes = [
        {
          "attribute_id": 1210,
          "attribute_display_name": "Product Type",
          "attribute_code": "product_type",
          "attribute_field_type": "Textfield",
          "cvl_option_values": [],
          "validation_rules": {}
        },
        {
          "attribute_id": 902,
          "attribute_display_name": "VAT",
          "attribute_code": "vat",
          "attribute_field_type": "dropdown",
          "cvl_option_values": [
            {
              "option_id": "5",
              "value": "5%"
            },
            {
              "option_id": "6",
              "value": "Exempt"
            }
          ],
          "validation_rules": {}
    }];
})

问题可能出在这里:

element.html(template);
ctrl.compile(element.html());  //try to bind template to outer scope

element.html() returns a html 作为字符串,而不是 ACTUAL dom 内容,因此您插入到指令元素中的内容实际上从未被编译angular,解释您的(不存在)行为。

element.append(ctrl.compile(template));

应该会更好。

对于需要父控制器的指令,我也会更改您的 ctrl.compile 方法(此处重命名为 insertAndCompile)

ctrl.insertAndCompile = function(content) {
    $compile(content)($scope, function(clone) {
        $element.append(clone);
    }
}

你只需要这样称呼它:

ctrl.insertAndCompile(template);

而不是我给出的第一个答案的 2 行。

我建议使用模板而不是 html 手动编译。 solution 更简单:

控制器将包含数据声明:

app.controller('ProductDetailsController', function($scope) {
  $scope.prodAttribs = {
    name: '',
    description: '',
    price: [0.0],
    condition: null
  }
  $scope.all_attribs = [{
    "attribute_id": 1210,
    "attribute_display_name": "Product Type",
    "attribute_code": "product_type",
    "attribute_field_type": "Textfield",
    "cvl_option_values": [],
    "validation_rules": {}
  }, {
    "attribute_id": 902,
    "attribute_display_name": "VAT",
    "attribute_code": "vat",
    "attribute_field_type": "dropdown",
    "cvl_option_values": [{
      "option_id": "5",
      "value": "5%"
    }, {
      "option_id": "6",
      "value": "Exempt"
    }],
    "validation_rules": {}
  }];
});

你的指令就这么简单:

app.directive('productAttribute', function() {
  return {
    restrict: 'A',
    scope: {
      attribModel: '=',
      prodAttribute: '=productAttribute'
    },
    templateUrl: 'template.html',
    controller: function($scope) {}

  }
});

template.html 将是:

<div>
  <select ng-show="prodAttribute.attribute_field_type.toLowerCase() == 'dropdown'" class="cvl" id="" ng-model="prodAttribs.attribute_code">
    <option value="">Select One</option>
    <option ng-repeat="item in prodAttribute.cvl_option_values track by $index"  value="{{item.value}}">{{item.value}}</option>
  </select>
  <input ng-show="prodAttribute.attribute_field_type.toLowerCase() == 'textfield'" type="text" id="{{prodAttribute.attribute_code}}" ng-model="prodAttribute.attribute_code">
</div> 

还有你的html:

<div ng-controller="ProductController"> 
    <div ng-repeat="attrib in all_attribs" product-attribute="attrib">{{attrib}}</div>
</div>