var myApp = angular.module("problemApp", []);
myApp.controller("RESTCall", function ($scope, $compile, $element, $timeout) {
$scope.username = 'Adan';
console.log($scope.username)
$scope.printValue = function(data) {
$timeout(function () {
$scope.$apply(function(){
console.log(data);
});
});
}
});

table td, th{
border: 1px solid black;
}

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<div ng-app="problemApp">
<div ng-controller="RESTCall">
<form name="covertToProForm" id=
"table-print">
<table id="confirm">
<tr>
<th>Firstname</th>
<td contentEditable ng-keyup="printValue(username)" ng-model="username">{{username}}</td>
</tr>
<tr>
<th>Lastname</th>
<td>Smith</td>
</tr>
</table>
</form>
</div>
</div>
&#13;
我上面的表格中有td
,其中包含contentEditable
属性。在编辑td
的值时,我想在控制台中打印它的值。任何帮助将不胜感激!
使用给定答案编辑的代码段。它没有用。
答案 0 :(得分:0)
请忽略我之前的回答。整个问题是我们需要将contenteditable
包装在自定义指令中,因为contenteditable
指令不能直接使用angular ng-model
,因为它会在每次更改时重新呈现dom元素,从而导致放弃最近的ng-model
更改。
这是wrapper
contenteditable
var app = angular.module('app', []);
app.directive('contenteditable', function() {
return {
restrict: "A",
require: 'ngModel',
controller: function($scope) {
$scope.username = 'Adan';
$scope.printValue = function() {
console.log($scope.username);
}
},
link: function(scope, element, attrs, myController) {
element.on('keyup', function() {
scope.$apply(updateViewModel);
});
function updateViewModel() {
var htmlValue = element.text()
myController.$setViewValue(htmlValue);
scope.printValue();
}
myController.$render = updateHtml
function updateHtml() {
var viewModelValue = myController.$viewValue
element.text(viewModelValue);
}
}
};
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.2.7" data-semver="1.2.7" src="https://code.angularjs.org/1.2.7/angular.js"></script>
<link href="style.css" rel="stylesheet" />
<script src="script.js"></script>
</head>
<body>
<div>
<h2>{{username}}</h2>
<form>
<table>
<tr>
<th>Firstname</th>
<td contenteditable ng-model="username">{{username}}</td>
</tr>
<tr>
<th>Lastname</th>
<td>Smith</td>
</tr>
</table>
</form>
</div>
</body>
</html>