简体   繁体   English

在$ scope。$ watch函数内不断收到“ TypeError:无法读取null的属性'value'”

[英]Keep getting “TypeError: Cannot read property 'value' of null” inside of $scope.$watch function

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. 我试图从一个容器中获取一个值,该容器的值发生变化时会触发一个$ scope。$ watch来启动另一个函数。 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. 我怀疑$watch在color变量有机会初始化之前就已加载。

My AngularJS Script: 我的AngularJS脚本:

'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: $watch函数$watch以下HTML代码块:

        <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. 首先从您的html中删除readonlyvalue属性。

<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. 现在在您的控制器中,当页面中的ng-model发生更改时, $scope.color的值应该已经自动更新。

In case if you want to use the $watch functionality then, here it is. 如果您要使用$ watch功能,就在这里。

$scope.$watch(function()
    {
       return $scope.color
    },
    function(newVal,oldVal){
       if (oldVal!==newVal){
          console.log('Color has changed to ' + newVal);
          hexToRGB(newVal);
       }
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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