我正在尝试向模型属性添加$watch
,并且我遇到了一个问题,如果初始值有空格,则会抛出错误;这就是我设置它的方式。
$scope.$watch($scope.Name, function (n, o) {
console.log('updating name: ', n);
});
这对应于HTML ...
<span name="name" contenteditable strip-br="true" ng-model="Name" class="profile-name" />
我使用以下绑定来处理contenteditable
angular.module('ui.editable', ['ngSanitize']).
directive('contenteditable', ['$sce','$sanitize', function($sce, $sanitize) {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if (!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function () {
element.html($sanitize(ngModel.$viewValue || ''));
};
// Listen for change events to enable binding
element.on('blur keyup change', function () {
scope.$apply(readViewText);
});
// Write data to the model
function readViewText() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if (attrs.stripBr && html == '<br>') {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
}]);
总而言之,我在尝试运行此代码时出现此错误
错误:[$ parse:syntax]语法错误:Token&#39; Lynn&#39;在[Lynn]开始的[Stacey Lynn]表达的第8列是一个意外的标记。
我不知道为什么会发生这种情况。我之前从未遇到过这样的事情。
如果名称不包含空格,则没有错误。手表成功初始化后,如果值更改为包含空格的值,则似乎没有任何错误。
答案 0 :(得分:0)
试一试:
$scope.$watch('Name', function (n, o) {
console.log('updating name: ', n);
});