我对AngularJs很陌生,我正在构建一个小应用程序来挑战自己。
初看起来非常简单:我希望能够选择多个条件,然后根据所选标准选择一个值,以便我们以后可以过滤数据。 因此,我想保持一个"标准值" couple数组稍后将其发送到服务器。
到目前为止,我所做的只是:plunker
错误是所有"选择"指令依赖于彼此...... 我知道问题来自模型变量的范围" chosenValue"和" selectedCriterion"它们由所有指令共享但如何将它们区域设置为属于该类的一个div" _new_criterion"并同时访问数组allChoices?
另外,我应该如何填充我的" allChoices"对象有类似
的东西[
{
criterion : "CITY",
value : "San Francisco"
},
{
criterion : "COMPANY",
value : "Something"
}
]
我不知道这是否是实现这一目标的正确方法,所以请随意提出其他解决方案。
以下是该应用的源代码示例:
var app = angular.module('app', []);
angular.module('app').controller('MainCtrl', function($scope, $compile) {
$scope.allCouples = [];
$scope.add = function(ev, attrs) { //$on('insertItem',function(ev,attrs){
var criterionSelector = angular.element(document.createElement('criteriondirective'));
var el = $compile(criterionSelector)($scope)
angular.element(document.body).append(criterionSelector);
};
});
app.directive('criteriondirective', function($compile) {
return {
template: '<div class="_new_criterion"><select ng-model="chosenCriterion" ng-change="chooseCriterion(chosenCriterion)" ng-options="criterion.columnName for criterion in criteria" class="form-control"></select></div>',
restrict: 'E',
replace: true,
transclude: false,
compile: function(tElement, tAttrs, transclude) {
return function(scope, element, attr) {
scope.chooseCriterion = function(sel) {
var valueSelector = angular.element(document.createElement('valuedirective'));
var el = $compile(valueSelector)(scope);
tElement.append(valueSelector);
};
//rest call to get these data
scope.criteria = [{
columnName: 'turnover',
type: 'range'
}, {
columnName: 'city',
type: 'norange'
}, {
columnName: 'company',
type: 'norange'
}];
};
}
};
});
app.directive('valuedirective', function() {
return {
template: '<select ng-model="chosenValue" ng-options="value for value in values" ng-change="chooseValue(chosenValue)" class="form-control"></select>',
restrict: 'E',
replace: true,
transclude: false,
compile: function(tElement, tAttrs, transclude) {
return function(scope, element, attr) {
scope.chooseValue = function(sel) {
//I would like to register the couple "criterion-value" into the array allCouples how to pass the criterion as parameter to this directive ?
// scope.allCouples.push({criterion : "criterion", value : "value"});
};
//Rest call to get these data
scope.values = ["Paris", "San Francisco", "Hong-Kong"];
};
}
};
});
非常感谢
p.s。:不要过多关注数值数组,实际情况下数据是否被提取