[英]Angular directive add template on textbox (enter of Spacebar)
我正在使用angular js,我的目標是在文本框中(空格鍵輸入)上顯示一個html表,並在該文本框中添加該表的元素,為此我寫了一條指令,但是我不確定是否完成了它在正確的道路上..好吧,我會詳細顯示它以便更清楚
這是我的HTML文本框
<input type="text" helps ng-model="firstText" code="1">
<div class="col-xs-4 pull-right" helps donotapply=true></div> //Do i need this??
這里的helps
是我的指令,它將我的html綁定到div,這是我的指令代碼
app.directive('helps', ['$parse', '$http','$filter', function ($parse, $http,$filter) {
return {
restrict: 'AE',
scope: true,
templateUrl: 'Table.html',
link: function (scope, element, attr) {
console.log(element);
element.bind("keypress", function (event) {
if (event.which === 114 || event.which === 32) {
scope.enterMe = function () { // this is to add data to Table
scope.newArray = [
{'code' :1,'name' : 'name1','age' : 24},
{'code' : 2,'name' : 'name2','age' : 26},
{'code' : 3,'name' : 'name3','age' : 25}
]
};
scope.setElement = function (element) { // Here set element function is to add my table name to textbox
var modelValue = tempattr.ngModel + '_value';
var model = $parse(tempattr.ngModel);
model.assign(scope, element.name);
modelValue = tempattr.ngModel + '_value';
modelValue = $parse(modelValue);
modelValue.assign(scope, element.code);
};
}
}
});
}
}
}]);
現在在這里我的Table.html
<div class="col-xs-4 pull-right" ng-show="hideMyMtHelpDiv">
<input type="text" ng-model="searchText" placeholder="search">
<input type="button" ng-model="gad" value="GO" ng-click="enterMe();">
<table ng-show="getTableValue" class="table table-bordered table-responsive table-hover add-lineheight table_scroll">
<thead>
<tr>
<td>
Code
</td>
<td>
Name
</td>
<td>
Age
</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="test in newArray" ng-dblclick="setElement(test);">
<td>
{{test.code}}
</td>
<td>
{{test.name}}
</td>
<td>
{{test.age}}
</td>
</tr>
</tbody>
</table>
</div>
現在的問題是,我的表已與div以及輸入文本框綁定; 那么,有什么適當的方法可以做到這一點嗎?
如果我的問題仍然不清楚,請發表評論。 感謝您的任何幫助
在此處檢查我的放屁者https://plnkr.co/edit/lAUyvYKp1weg69CsC2lg?p=preview並閱讀自述文件
首先,您在input和div中都使用save指令。 您可以將它們分開作為第一步:
mod.directive('onKeydown', function() {
return {
restrict: 'A',
scope: {
setShowSearch: '&'
},
link: function(scope, elem, attrs) {
elem.on('keydown', function(event){
if (event.which === 114 || event.which === 32) {
setShowSearch()(true);
}
});
}
};
});
然后,您可以傳遞一個函數來將showSearch變量設置為該指令,並在您的輸入中使用它:
<input type="text" ng-model="firstText" hpcode="1" on-keydown="" set-show-search="setShowSearch"/>
現在, setShowSearch
在您的controller
而不是您的directive
因此它具有自己的scope
。
myApp.controller('MyController', ['$scope', function($scope) {
$scope.setShowSearch = function(show) {
//do whatever you want here
};
$scope.msg = 'This Must Work!';
}]);
完成后,您現在有了一個干凈的指令,該指令負責顯示表,其余指令只是以類似的方式將該數組傳遞給該指令。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.