Angularjs 我的指令范围定义有什么问题?
我的表单中有几个Angularjs 我的指令范围定义有什么问题?,angularjs,angularjs-directive,scope,Angularjs,Angularjs Directive,Scope,我的表单中有几个字段。我想动态加载这些选项,所以我使用ng repeat遍历可以随数据对象移动的选项列表 为了使此功能更加可重用,我中断了这段代码并创建了一个指令: javascript: angular.module( "ngFamilyTree" ) .directive( "selectInput", function(){ return { restrict: "E", templateUrl: "templates
字段。我想动态加载这些选项,所以我使用ng repeat遍历可以随数据对象移动的选项列表
为了使此功能更加可重用,我中断了这段代码并创建了一个指令:
javascript:
angular.module( "ngFamilyTree" )
.directive( "selectInput", function(){
return {
restrict: "E",
templateUrl: "templates/directives/selectInput.html",
scope: {
element: "=",
options: "=",
change: "="
}
};
} );
模板/指令/selectInput.html:
<select ng-model="element" class="form-control">
<option ng-repeat="(text, value) in options" value="{{value}}">{{text}}</option>
</select>
{{text}}
在初级形式中,我在不同的地方使用以下指令元素:
<select-input element="docCntl.document.type" options="docCntl.document.typeOptions"></select-input>
<select-input element="docCntl.document.category" options="docCntl.categoryOptions" change="docCntl.document.updateSubCategoryOptions()"></select-input>
<select-input element="docCntl.document.subcategory" options="docCntl.subCategoryOptions"></select-input>
我觉得奇怪的是,第一个实例中,我将元素设置为“docCntl.document.type”,效果非常好。每次更改select的值时,模型对象中相应元素的值都会更改。但是,第二项和第三项不会更改模型值
此外,我也尝试过使用和不使用“change”属性。这样做的目的是能够设置一个更新函数,在类别更改时更改子类别的可用选项
注意:我有意将类别选项和子类别选项存储在docCntl中,而不是存储在docCntl.document中;这就是为什么它们看起来与类型选择器可用的选项不同的原因
注2:类别和子类别在初始页面加载时使用正确的选项正确加载。您阅读了吗?您可以使用ng options指令来实现相同的结果
您可以在标记中使用类似的内容-
希望这有帮助:)你读过吗?您可以使用ng options指令来实现相同的结果
您可以在标记中使用类似的内容-
希望这有帮助:)试试这个解决方案
ngFamilyTree.directive(“selectInput”,function()){
返回{
限制:“E”,
templateUrl:“模板/指令/selectInput.html”,
范围:{
元素:“=”,
选项:“=”,
更改:“=”,
父范围:“=”
},
链接:功能(范围){
scope.cascade=函数(val){
if(type of scope.change==‘function’){
scope.change(scope.parentScope、scope.element);
}
};
}
};
});代码>尝试此解决方案
将父作用域对象添加到指令中。您可以使用根作用域,但这不是一个好的做法。注意添加了parentScope、link和cascade
ngFamilyTree.directive(“selectInput”,function()){
返回{
限制:“E”,
templateUrl:“模板/指令/selectInput.html”,
范围:{
元素:“=”,
选项:“=”,
更改:“=”,
父范围:“=”
},
链接:功能(范围){
scope.cascade=函数(val){
if(type of scope.change==‘function’){
scope.change(scope.parentScope、scope.element);
}
};
}
};
});代码>
<select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
$scope.items = [{
id: 1,
label: 'aLabel',
subItem: { name: 'aSubItem' }
}, {
id: 2,
label: 'bLabel',
subItem: { name: 'bSubItem' }
}];