Ciel Ciel - 1 year ago 116
AngularJS Question

angular cannot seem to understand text with spaces in $watch expression

I am attempting to add a

to a model property, and I'm running into an issue where, if the initial value has a space, it throws an error; this is how I've set it up.

$scope.$watch($scope.Name, function (n, o) {
console.log('updating name: ', n);

This corresponds to the HTML ...

<span name="name" contenteditable strip-br="true" ng-model="Name" class="profile-name" />

I am using the following binding to work with

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 () {

// 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 = '';

altogether, I get this error when I try to run this code

Error: [$parse:syntax] Syntax Error: Token 'Lynn' is an unexpected token at column 8 of the expression [Stacey Lynn] starting at [Lynn].

I'm at a loss as to why this is happening. I've never encountered something quite like this before.

If the name does not contain spaces, there is no error. Once the watch initializes successfully, there do not appear to be any errors if the value changes to one that contains spaces.

Answer Source

Try it:

$scope.$watch('Name', function (n, o) {
    console.log('updating name: ', n);