我有一个包含以下两个块的网络表单:
<div class="mm-FilterRow">
<div>First Name:</div>
<div><i ng-hide="user.FirstName">Loading...</i><select ng-show="choices.FirstNames" ng-model="user.FirstName" ng-options="o as o for o in choices.FirstNames"></select></div>
</div>
<div class="mm-FilterRow">
<div>Last Name:</div>
<div><i ng-hide="user.LastName">Loading...</i><select ng-show="choices.LastNames" ng-model="user.LastName" ng-options="o as o for o in choices.LastNames"></select></div>
</div>
如您所见,这两者之间的唯一区别是范围变量“user.FirstName|user.LastName"
和选择选项”choices.FirstNames|choices.LastNames
“
因为我有大约10个相同结构的div我想做的事情:(这是伪代码,不工作)
<div ng-include="singlerow.html" caption="First name" scopetarget="user.FirstName" scopeSource="choices.FirstNames">
<div ng-include="singlerow.html" caption="Last name" scopetarget="user.LastName" scopeSource="choices.LastNames">
有机会实现我想要的吗?或者我是否必须保留那些丑陋的复制/粘贴变体?
答案 0 :(得分:1)
这是不可能的,在这种情况下更好地使用directives。
angular.module('DirectiveExample', [])
.controller('Controller', ['$scope', function($scope) {
$scope.options = [1, 2, 3];
$scope.field = "Test";
}])
.directive('singlerow', function() {
return {
restrict: 'E',
scope: {
field: '=',
options: '=',
},
templateUrl: '/singlerow.html'
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="DirectiveExample">
<script type="text/ng-template" id="/singlerow.html">
<div class="mm-FilterRow">
<div>Last Name:</div>
<div><i ng-hide="field">Loading...</i><select ng-show="options" ng-model="field" ng-options="o as o for o in options"></select></div>
</div>
</script>
<div ng-controller="Controller">
<singlerow field="field" options="options"></singlerow>
</div>
</div>
&#13;