2015-09-06 57 views
1

我正在尝试创建一个使用Angular动态构建表单域的组件(这是我的新手)。使指令范围对每个指令都是唯一的?

控制器包含表单字段我将被观看的数据作为mainModel如下:

angular.module('formExample', []) 
    .controller('ExampleController', ['$scope', function ($scope) { 

    // build the scope dynamically 
    $scope.mainModel = { 
     "category_id": { 
      "name": "category_id", 
       "value": "1", 
       "label": "Category Id" 
     }, 
      "category_name": { 
      "name": "category_name", 
       "value": "First Category", 
       "label": "Category Name" 
     }); 

}]).directive('formLoader', function ($compile) { 

    function link(scope, ele, attrs) { 

     var html = ''; 
     jQuery.each(scope.mainModel, function (key, value) { 
      //display the key and value pair 
      console.log(key + ' --------------- ' + value); 

      if (key == 'category_id' || key == 'category_name') { 
       html += "<br />Testing<br /><kad-Input properties='mainModel." + key + "'></kad-Input>" 
      } 

     }); 

     var x = angular.element(html); 
     ele.append(x); 
     $compile(x)(scope); 

    } 

    return { 
     restrict: 'E', 
     scope: false, 
     link: link 
    }; 

}).directive('kadInput', function ($parse) { 
    return { 
     restrict: 'E', 
     //transclude: true, 
     scope: false, 
     templateUrl: 'tests.html', 
     link: function (scope, ele, attrs) { 

      scope.properties = $parse(attrs.properties)(scope); 
      console.log(scope.properties); 

     } 
    }; 
}); 

的想法是遍历mainModel和建立动态基于主模型的形式,这是formLoader指令的作业,这是我将在我的HTML中调用的唯一的东西。

我创建了一个指令kadInput(只是用于测试),类似于一个“标签:文本输入” HTML如下:

<div class="col-lg-2 col-md-2 col-sm-12 bottom-10" > 
    <h4 class="header_label" ><label for="productName"> {{properties.label}} </label></h4> 
</div> 

<div class="col-lg-9 col-md-9 col-sm-12" > 
    <input type="text" id="productName" ng-model="properties.value" class="form-control" /> 
</div> 

我得到所需要的结果,但问题是,kadInputscope.properties并不是唯一的指令,它只是将最后设置的数据取出来。

如何让每个指令的作用域保持与我的代码相同的方面?

回答

1

您在这里做了很多不必要的事情,Angular指令您。我建议你仔细阅读directives guide-这很容易理解。

这里的相关要点是“隔离范围”的概念,您明确选择使用scope: false(顺便说一句,它什么也不做),然后手动从attrs读取,这主要是否定指令的设计目的。

什么是一个对象传递给scope,将指定要与单个参数的分离范围:

scope: { 
    properties: '=' 
} 

这将设置数据绑定的你,和它将使范围在您的指令的实例之间保持唯一。

+0

我有一些概念混在一起...但现在你明白了我感谢的人.. – KAD

+0

@KAD这是*女*,非​​常感谢你 –

+0

oops(* ^∀^ *)..谢谢淑女 :) – KAD