gpt4 book ai didi

javascript - 使每个指令的指令范围都是唯一的?

转载 作者:行者123 更新时间:2023-11-27 23:54:01 25 4
gpt4 key购买 nike

我正在尝试创建一个使用 Angular(我是新手)动态构建表单字段的组件。

Controller 包含我将在 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 指令不是唯一的,它只获取最后的数据设置为它。

如何使每个指令的范围唯一并保持代码的相同方面?

最佳答案

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

这里的相关点是“隔离范围”的想法,您可以通过使用 scope: false (顺便说一句,它什么也不做)来明确选择退出,然后阅读手动从 attrs 中获取,这主要是否定指令的设计目的。

想要是将一个对象传递给scope,该对象将指定您想要一个具有单个参数的隔离范围:

scope: {
properties: '='
}

这将为您设置数据绑定(bind),并保持指令实例之间的范围唯一。

关于javascript - 使每个指令的指令范围都是唯一的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32427504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com