how can I use a color code in a String variable and link this variable to a $watch expression?
$scope.$watch($scope.backgroundTextColor, function(){
// code inside function
});
With the example code I get the next error:
"Error: [$parse:lexerr] Lexer Error: Unexpected next character at columns 0-0 [#] in expression [#9c5c5c]...
You are passing the Value of $scope.backgroundTextColor
You need to pass the name of the variable eg
$scope.$watch('backgroundTextColor', function(newValue, oldValue){
// code inside function
});
Have a look at Responding to Scope Changes
You are trying to use a magic string here.
The $watch
function in Angular can either take in a function that returns the value that you want to watch, or a string that refers to the variable that you want to watch (a magic string).
The string will refer to the variable as if you are in the HTML. So if you are using the $scope
(which it looks like you are) you need:
$scope.$watch('backgroundTextColor', function(newValue, oldValue){
// code inside function
});
If you have an alias set (using ControllerAs
for example) for the controller you will need to reference that:
$scope.$watch('ctrl.backgroundTextColor', function(newValue, oldValue){
// code inside function
});
Otherwise you can use a function:
$scope.$watch(function() {
return $scope.backgroundTextColor;
}, function(newValue, oldValue){
// code inside function
});
Rather then placing the variable as is in the $watch
expression, try to return the variable value:
$scope.$watch(function() { return $scope.backgroundTextColor }, function() {
// code inside function
});
I prefer using the variable itself and not its HTML string representation ( backgroundTextColor
), this way you are more agnostic to the view.
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.