I'm trying to get a value from a container that, on a change in its value, triggers a $scope.$watch that starts another function. I can only get the error above, even though I can confirm that it is retrieving the correct value. My suspicion is that $watch
is loading before the color variable has a chance to initialize.
My AngularJS Script:
'use strict';
angular.module('careApp.tMain', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/tMain', {
templateUrl: './templates/tMain.html',
controller: 'tMainCtrl'
});
}])
.controller('tMainCtrl', function($scope, $http) {
$scope.dimmer = 100;
$scope.color = '#c24747';
$scope.$watch('color', function(){
console.log('Color has changed to ' + $scope.color);
hexToRGB($scope.color);
})
});
The $watch
function watches over the following chunk of HTML code:
<div>
<!-- $watch looks for changes here-->
<ng-farbtastic ng-model="color"></ng-farbtastic>
<md-input-container class="hide">
<label>Color</label>
<!-- Curly brace 'color' variable from farbtastic.js code -->
<input type="text" value="{{color}}">
</md-input-container>
</div>
What do I need to do to correct this error?
First remove the readonly
and value
attribute from your html.
<md-input-container class="hide">
<label>Color</label>
<input type="text" ng-model='color'>
</md-input-container>
Now in your controller, the value of the $scope.color
should have been updated automatically when there is a change in the ng-model from your page.
In case if you want to use the $watch functionality then, here it is.
$scope.$watch(function()
{
return $scope.color
},
function(newVal,oldVal){
if (oldVal!==newVal){
console.log('Color has changed to ' + newVal);
hexToRGB(newVal);
}
});
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.