简体   繁体   中英

In angular js why does this javascript replace method to replace &nbsp works on the controller side but not on the template side

Template angular expression:

<h2 style="white-space:normal">
    {{notification.noti_val.replace(/\&nb\s*sp;/g, ' ')}}
</h2>

does not work

function TodoCtrl($scope) {
    $scope.notification = 'ujjal saha&nbsp;share&nbsp;own&nbsp;wall';
    $scope.notif = notification.noti_val.replace(/\&nb\s*sp;/g, '') 
} 

works

This does not work because angular expressions are not exactly same as javascript expressions . In your example you are trying to create a regular expression and evaluate it. As mentioned on angular documentation angular expressions do not allow No RegExp Creation With Literal Notation . And since angularjs expressions are forgiving no error is thrown but your code doesn't work silently

Why not just create a filter? As stated by @AdityaSingh above, angular expressions are not exactly like JavaScript expressions, which is why filters were created.

JS:

angular.module('MODULE_NAME').filter('stripSpaces', function() {
    return function(input) {
        return input.replace(/\&nb\s*sp;/g, '');
    }
}

HTML:

{{notification.noti_val | stripSpaces}}

Look at your code closely.

$scope.notification = 'ujjal saha&nbsp;share&nbsp;own&nbsp;wall';
$scope.notif = notification.noti_val.replace(/\&nb\s*sp;/g, '');

You have $scope.notification = but later try to edit notification.noti_val

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM