我开发了一个有角度的应用程序,我想通过具有'日期'类型的输入替换某些关键字,如'[input-date]'。
我尝试使用Regexp替换功能,但不起作用。它显示的是代码,而不是输入。
我能够使用ng-bind-html显示输入,但我无法使用ng-model的值。
<body ng-controller="MainCtrl">
<div ng-bind-html="trustAsHtml(output)"></div>
<p>{{inputValue}}</p>
</body>
var app = angular.module('plunker', ['ngSanitize']);
app.controller('MainCtrl', function($scope, $sce) {
$scope.trustAsHtml = $sce.trustAsHtml;
$scope.foo = 'some text {val}';
var regexValue = new RegExp("{val}", "g");
$scope.output = $scope.foo.replace(regexValue, '<input type="text" name="some_name" ng-model="inputValue" value="">');
});
http://plnkr.co/edit/nmML6X7y6poRvY6eY3K5
修改
我尝试类似的东西
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-sanitize.js"></script>
</head>
<body ng-app="plunker">
<div ng-controller="MainCtrl">
<p ><date-input model="output" information="info"></date-input></p>
</div>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.output = 'Johan';
$scope.info = [{
"id": 0,
"name": "i'm a name",
"type": "text",
"message": "Hello, i'm {{value}} and i love cacao"
}];
}]).directive('dateInput', function() {
return {
restrict: 'E',
scope: {
model: '=model',
information: '=information'
},
template: function(){
var regexValue = new RegExp("{{value}}", "g");
return information.message.replace(regexValue, '<input type="date" ng-model="model">');
}
};
});
</script>
</body>
</html>
但是
错误:无法找到变量:信息
答案 0 :(得分:0)
在控制器中操作DOM不是一个好主意。 AngularJS有这样的指令:
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular-sanitize.js"></script>
</head>
<body ng-app="plunker">
<div ng-controller="MainCtrl">
<p><date-input name="info.name" message="info.message"></date-input></p>
</div>
<script>
var app = angular.module('plunker', []);
app.controller('MainCtrl', ['$scope', function($scope) {
$scope.info = {
"id": 0,
"name": "Kostya",
"type": "text",
"message": "Hello, i'm {{name}} and i love cacao"
};
}]).directive('dateInput', ['$compile', function($compile) {
return {
restrict: 'E',
scope: {
name: '=name',
message: '=message'
},
template: '<span class="message">{{message}}</span><br>\n\
<input type="date" ng-model="name">',
link: function (scope, element, attrs) {
scope.info = $compile(element.children('.message'))(scope);
scope.$watchCollection(['message', 'name'], function(newValues, oldValues, scope) {
scope.info = $compile(element.children('.message'))(scope);
});
}
};
}]);
</script>
</body>
</html>
&#13;