javascript - 继续在 $scope.$watch 函数内获取 "TypeError: Cannot read property ' value' of null"

标签 javascript html angularjs

我试图从容器中获取一个值,当其值发生变化时,会触发 $scope.$watch 来启动另一个函数。尽管我可以确认它正在检索正确的值,但我只能得到上面的错误。 我怀疑 $watch 在颜色变量有机会初始化之前加载。

我的 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);
  })
});

$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>

我需要做什么来纠正此错误?

最佳答案

首先从 html 中删除 readonlyvalue 属性。

<md-input-container class="hide">
   <label>Color</label>
   <input type="text" ng-model='color'>
</md-input-container>

现在,在您的 Controller 中,当页面中的 ng-model 发生更改时,$scope.color 的值应该会自动更新。

如果您想使用 $watch 功能,就在这里。

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

关于javascript - 继续在 $scope.$watch 函数内获取 "TypeError: Cannot read property ' value' of null",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996892/

相关文章:

html - 使用 Z-index,边距无法将 div 推离另一个

javascript - 在 Angular 中从 nodejs 获取 JSON

javascript - 使用 AngularJS 服务构建 html 部分

Javascript 获取方法

javascript - Knockout - 通过设置对象的属性来更改对象的 'subclass'

javascript - 使用 promise 作为回调来 react setState

java - HTML 中 CSS 文件的绝对网络路径?

javascript - 计算卷轴上的数字

javascript - 从 ng-repeat 获取实际的数组索引

javascript - AngularJS 选择必需