2

我已经在 Angular 的隔离范围中苦苦挣扎了超过 24 小时。这是我的场景:我对一个ng-repeat对象数组进行了迭代,我想从中使用自定义指令来生成一个<select><input>基于field_type当前被迭代对象的属性。这意味着我必须$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": {}
    }];
})
4

2 回答 2

1

问题可能在这里:

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

element.html() 将 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 行。

于 2016-01-12T13:49:39.370 回答
1

我建议手动使用模板而不是 html 编译。解决方案要简单得多:

控制器将包含数据声明:

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>
于 2016-01-12T14:15:14.983 回答