我得到像ReferenceError这样的错误:没有定义matchcolor

时间:2017-03-11 17:12:30

标签: javascript angularjs ionic-framework

我正在生成随机颜色的瓷砖。所有瓷砖都是相同颜色,除了一个。那一个有浅色。如果用户找到并单击该浅色瓷砖。然后板生成另一个颜色块。同样的逻辑。它在简单的html,css,javascript https://js.do/code/141376中运行良好,但是当我在离子瓷砖板中进行转换时会创建但是当我点击瓷砖时我会收到类似ReferenceError的错误:matchcolor未定义。

HTML

<ion-view view-title="Dashboard">
 <ion-content class="padding">
  <div ng-controller="helloCtrl">
    <div id="color_board"></div>
  </div>
 </ion-content>
</ion-view>

JS

.controller('helloCtrl', [ '$scope',function($scope) {

 $scope.getRandomColor = function() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}


$scope.ColorLuminance =  function(hex, lum) {
  hex = String(hex).replace(/[^0-9a-f]/gi, '');
  if (hex.length < 6) {
    hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
  }
  lum = lum || 0;
  var rgb = "#", c, i;
  for (i = 0; i < 3; i++) {
    c = parseInt(hex.substr(i*2,2), 16);
    c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
    rgb += ("00"+c).substr(c.length);
  }
  return rgb;
}

$scope.shuffle = function(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;
  while (0 !== currentIndex) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }
  return array;
}

$scope.colorboard = function(){

  var colors = $scope.getRandomColor();
  console.log('random');
  var light = $scope.ColorLuminance(colors,0.3);
  console.log('light');
  console.log(light);
  var arr = [];
  for(var i=1; i<=23; i++) {
     arr.push(colors);
  }
  arr.push(light);
  $scope.shuffle(arr);
  console.log('shuffle');


  var output = '';
  for (var i = 0; i < arr.length; i++) {
    output += '<div id="color_tile_'+i+'" style="background:'+arr[i]+';" ng-Click="matchcolor(\''+arr[i]+'\',\''+light+'\')"></div>';
  }
  document.getElementById('color_board').innerHTML = output;
}

$scope.matchcolor = function(val,light){
  console.log(light);
  console.log(val); 
  if(val == light)
  { 
    colorboard();
  }

}

$scope.colorboard();



}])

1 个答案:

答案 0 :(得分:0)

您的函数仅在控制器内部已知,如果您希望在视图中知道函数,则需要将它们定义为$ scope的属性。您在视图中使用的变量和函数必须是范围的属性。

$scope.matchcolor = function(val,light){
  console.log(light);
  console.log(val); 
  if(val == light)
  { 
    colorboard();
  }

}

您还需要将DI样式更改为推荐的样式,因为当您将应用程序转换为离子时,所有代码都会缩小并且您的依赖项变得未知,您需要更改它:

.controller('helloCtrl', [ '$scope',function($scope) {
//code here
}])