当用户执行特定操作时,我尝试将带有 ng-model 属性的新 HTML 元素附加到 p 标记,但 ng 模型不起作用。 这是我的代码。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
p{
height: 600px;
width: 600px;
font-size:17px;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="editor">
<label for="kys_font_size"> font size:</label>
<select ng-model="kys_selected_font" id="fontsize" name="kys_font_size" ng-options="page for page in FontSize(1, 150)" ng-change="changeFont()">
</select>
<p contenteditable="true" id="content" >
</p>
<p>{{fonttext}}</p>
</div>
<p></p>
<script>
var app = angular.module('myApp',[]);
app.controller('editor',function($scope){
$scope.fonttext="hello";
$scope.FontSize = function(start, end) {
var size = [];
for (var i = start; i <= end; i++) {
size.push(i);
}
return size;
};
$scope.changeFont = function(){
$("#content").append("<p size='3' ng-model='fonttext' id='one'> This is some text </p>");
$("#one").focus();
}
});
</script>
</body>
</html>
我该如何解决这个问题?有人会深入解释为什么 ng-model 在这里不起作用吗?
最佳答案
首先我不知道你想在这里实现什么目标。但您需要 $compile
附加元素。您需要先将 $compile
函数注入(inject)到 Controller 中。
其次,p
标签不会接受任何ng-model
。我将其更改为输入,您可以看到模型值(“Hello”)正在加载。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
p {
height: 600px;
width: 600px;
font-size: 17px;
}
</style>
</head>
<body>
<div ng-app="myApp" ng-controller="editor">
<label for="kys_font_size">font size:</label>
<select ng-model="kys_selected_font" id="fontsize" name="kys_font_size" ng-options="page for page in FontSize(1, 150)" ng-change="changeFont()">
</select>
<p contenteditable="true" id="content">
</p>
<p>{{fonttext}}</p>
</div>
<p></p>
<script>
var app = angular.module('myApp', []);
app.controller('editor', function($scope, $compile) {
$scope.fonttext = "hello";
$scope.FontSize = function(start, end) {
var size = [];
for (var i = start; i <= end; i++) {
size.push(i);
}
return size;
};
$scope.changeFont = function() {
$("#content").append($compile("<input size='3' ng-model='fonttext' id='one' /> This is some text")($scope));
$("#one").focus();
}
});
</script>
</body>
</html>
关于带有属性 ng-model 的 jQuery append() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36449956/