0
我很新的AngularJs和我建立與它的小應用程序,以挑戰自己。範圍和指令AngularJs
這是一見鍾情很簡單:我想可以選擇多個條件,然後選擇一個值的基礎上,選擇的標準,所以我們以後可以過濾數據。 因此,我想維護一個「標準值」夫婦數組,以便稍後將其發送給服務器。
所有到目前爲止,我所做的是在這樣的:plunker
的錯誤是,所有的「選擇」指令都依賴於彼此...... 我知道問題來自模型變量的作用域「 selectedValue「和」chosenCriterion「,它們被所有指令共享,但是如何使它們的語言環境變爲屬於類」_new_criterion「的一個div,並且同時訪問數組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"];
};
}
};
});
非常感謝您
PS:不支付太多注意值陣,在現實情況下,數據被取出REST風格
非常感謝你「的範圍:真正的」作品!不知道這個選擇 – Acen1991 2014-12-07 22:02:55