在我的 AngularJS 应用程序中,我到处都有不同的复杂输入。例如,某些输入具有使用 Google Places 自动完成功能或 Twitter Bootstrap 自动完成功能的指令。
我正在寻找一种方法来制作一个指令,当我们添加一些文本(如 iOS 功能)时,该指令会显示擦除按钮。
我做了这个,但是scope.erase
不启动,也不ng-show
.
是否可以在文本输入后添加 HTML 并在控制器内“播放”它们?
My test:
app.directive('eraseBtn', function($parse, $compile){
return {
require: 'ngModel',
restrict: "A",
transclude: true,
link : function(scope, element, attrs, model){
element.parent().append('<button ng-click="erase()" ng-show="model.length > 0" class="erase-btn">x</button>');
scope.erase = function(){
console.log('Erase test');
}
}
}
});
我不想使用模板,因为我所有输入的 HTML 都非常不同。
您可以根据模型的值在指令的链接函数内创建自定义输入。如果您希望将这些元素绑定到模型或使用指令来构建它们,您应该使用$compile
(并且不要忘记使用模型调用已编译的模板):
HTML
<!DOCTYPE html>
<html ng-app="demo">
<head>
<script data-require="angular.js@*" data-semver="1.2.10" src="http://code.angularjs.org/1.2.10/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="demoController">
<div demo-directive ng-repeat="input in inputs"></div>
</body>
</html>
JavaScript
angular.module('demo', []).
controller('demoController', function($scope) {
$scope.inputs = [{
inputType: 'checkbox',
checked: true,
label: 'input 1'
}, {
inputType: 'text',
value: 'some text 1',
label: 'input 2'
}];
$scope.doSomething = function() {
alert('button clicked');
};
}).
directive('demoDirective', function($compile) {
return {
template: '<div><label>{{input.label}}: </label></div>',
replace: true,
link: function(scope, element) {
var el = angular.element('<span/>');
switch(scope.input.inputType) {
case 'checkbox':
el.append('<input type="checkbox" ng-model="input.checked"/><button ng-if="input.checked" ng-click="input.checked=false; doSomething()">X</button>');
break;
case 'text':
el.append('<input type="text" ng-model="input.value"/><button ng-if="input.value" ng-click="input.value=\'\'; doSomething()">X</button>');
break;
}
$compile(el)(scope);
element.append(el);
}
}
});
笨蛋:http://plnkr.co/edit/pzFjgtf9Q4kTI7XGAUCF?p=preview http://plnkr.co/edit/pzFjgtf9Q4kTI7XGAUCF?p=preview
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)