我已经开发了一个指令,但它始终在页面的最后一个元素上应用功能,这是我的代码:
HTML:
<div ng-controller="MyCtrl">
<input type="text" email-commy comma-separated-data="model1" class="form-control"/>
<input type="text" email-commy comma-separated-data="model2" class="form-control"/>
</div>
JS:
var app=angular.module('myApp', []);
function MyCtrl($scope) {
$scope.model1 = "abc@gmail.com";
$scope.model2 = "abc2@gmail.com";
}
app.directive("emailCommy", function(){
return {
scope: {
commaSeparatedData: '='
},
restrict: "A",
multiple: true,
link: function (scope, elem, attrs, ngModel) {
function handler(dataString){
function buildEmailList() {
var lis = data.map(function (em, index) {
return "<li>" + em + "<span class='remove-element' data-index='" + index + "'>×</span>" + "</li>";
}).join("");
var input = $("<input/>", {"class": "form-control shadow-element", "placeholder": "Enter..."});
lis += "<li class='input-field'>" + input.wrap("<p/>").parent().html() + "</li>";
return "<ul class='list-inline'>" + lis + "</ul>";
}
function renderer() {
$wrapper.empty().append(buildEmailList());
elem.addClass("hide").before($wrapper);
listener();
}
function listener() {
angular.element(".shadow-element").off("keypress").on("keypress", function (evt) {
var $this = $(this),
charCode = evt.which || evt.keyCode;
//add input in case of (comma, enter, and semi-colon) pressed
if ($this.val() && (charCode === 44 || charCode === 13 || charCode === 59)) {
data.push($this.val().toLowerCase());
renderer();
updateModel();
$this.val("");
}
});
angular.element(".remove-element").off("click").on("click", function () {
var $this = $(this),
index = $this.data("index");
data.splice(index, 1);
updateModel();
renderer();
});
}
function updateModel(){
var updatedVal = data.join(",");
$(elem).val(updatedVal);
}
if(dataString) {
var data = dataString.split(",").map(function (em) {
return em.toLowerCase().trim();
});
var $wrapper = $("<div/>", {"class": "email-container"});
renderer();
}
}
handler(scope.commaSeparatedData);
//scope.$watch(attrs.commaSeparatedData, handler);
}
};
});
这是小提琴: http://jsfiddle.net/RmDuw/928/
指令仅适用于最后一个元素。如果我在第一个指令中添加数据,则会将其添加到一个以下。
请帮助,并建议我如何解决。 感谢
答案 0 :(得分:0)
只需更改代码即可选择当前指令的输入:
function listener() {
$wrapper.find('input').on(...
和删除元素:
$wrapper.find('span')..
请参阅fiddle