使用Angularjs中的观察器很难控制具有跨度值列表的数组对象。
部分工作,当我输入span元素时,会自动为每个跨度创建一个数组,当我删除任何span元素时 - > gt;将删除现有数组中的相应行,并正确地重新调整所有其他行(不会干扰值和名称)。
问题是当我删除一个span元素并使用我的输入文本重新输入它时,它没有被添加到我的数组中。因此,在删除一个span元素后,输入任何新元素 - 这些新值不会附加到我的数组中。
DemoCode 小提琴link
我的代码中缺少什么?
如何将重新插入的跨度附加到现有数组对象而不会干扰剩余行的值(数组的名称和值)?
请注意,根据图表,值会随时更改。
这是我正在使用的代码:
<script>
function rdCtrl($scope) {
$scope.dataset_v1 = {};
$scope.dataset_wc = {};
$scope.$watch('dataset_wc', function (newVal) {
//alert('columns changed :: ' + JSON.stringify($scope.dataset_wc, null, 2));
$('#status').html(JSON.stringify($scope.dataset_wc));
}, true);
$(function () {
$('#tags input').on('focusout', function () {
var txt = this.value.replace(/[^a-zA-Z0-9\+\-\.\#]/g, ''); // allowed characters
if (txt) {
//alert(txt);
$(this).before('<span class="tag">' + txt.toLowerCase() + '</span>');
var div = $("#tags");
var spans = div.find("span");
spans.each(function (i, elem) { // loop over each spans
$scope.dataset_v1["d" + i] = { // add the key for each object results in "d0, d1..n"
id: i, // gives the id as "0,1,2.....n"
name: $(elem).text(), // push the text of the span in the loop
value: 3
}
});
$("#assign").click();
}
this.value = "";
}).on('keyup', function (e) {
// if: comma,enter (delimit more keyCodes with | pipe)
if (/(188|13)/.test(e.which)) $(this).focusout();
if ($('#tags span').length == 7) {
document.getElementById('inptags').style.display = 'none';
}
});
$('#tags').on('click', '.tag', function () {
var tagrm = this.innerHTML;
sk1 = $scope.dataset_wc;
removeparent(sk1);
filter($scope.dataset_v1, tagrm, 0);
$(this).remove();
document.getElementById('inptags').style.display = 'block';
$("#assign").click();
});
});
$scope.assign = function () {
$scope.dataset_wc = $scope.dataset_v1;
};
function filter(arr, m, i) {
if (i < arr.length) {
if (arr[i].name === m) {
arr.splice(i, 1);
arr.forEach(function (val, index) {
val.id = index
});
return arr
} else {
return filter(arr, m, i + 1)
}
} else {
return m + " not found in array"
}
}
function removeparent(d1)
{
dataset = d1;
d_sk = [];
Object.keys(dataset).forEach(function (key) {
// Get the value from the object
var value = dataset[key].value;
d_sk.push(dataset[key]);
});
$scope.dataset_v1 = d_sk;
}
}
</script>
答案 0 :(得分:1)
使用angular我认为你会在html方面想要更多东西,特别是使用ng-repeat和ng-click和ng-model首先你要创建你的数组,这可以简单地在你的代码文件中完成或者使用ng-init。这是一个例子
AndroidManifest.xml
&#13;
(function(){
var app=angular.module('demoApp',[]);
app.controller('demoApp',[function(){
this.spans=[""];
this.currentSpan='';
this.addSpan=function(){
this.spans.push(this.currentSpan);
this.currentSpan='';
};
}]);
})();
&#13;