简体   繁体   中英

Angular variable not binding to view

I have an Angular/Onsen app that has an image which is put into a HTML5 canvas tag , and I am picking the color of the pixel I am on on hover .

The view is pretty simple:

  <ons-template id="live.html">
    <ons-page ng-controller="LiveController">
      <ons-toolbar>
        <div class="left">
          <ons-toolbar-button ng-click="menu.toggle()">
            <ons-icon icon="ion-navicon" size="28px" fixed-width="false"></ons-icon>
          </ons-toolbar-button>
        </div>
        <div class="center">Live Camera</div>
      </ons-toolbar>



      <canvas id="canvas" width="100" height="100"></canvas>

      <p>#{{hex}}</p>

    </ons-page>
  </ons-template>

You can see there that the <p> tag should be displaying the value of $scope.hex (the calculated hex value of the pixels rgb channels) but it is not. Even though the correct value is logging from my controller.

Here's my Controller :

  module.controller('LiveController', function($scope, $data) {

      $scope.hex = '00FFFF';
      var pictureSource;
      var destinationType;

      document.addEventListener("deviceready", onDeviceReady, true);

      function onDeviceReady() {
        console.log('onDeviceReady');
        pictureSource = navigator.camera.PictureSourceType;
        destinationType = navigator.camera.DestinationType;
        capturePhoto();

      }

      function capturePhoto() {
        console.log('capturePhoto');
        navigator.camera.getPicture(onSuccess, onFail, {
          quality: 50,
          destinationType: destinationType.DATA_URL
        });
      }

      function onSuccess(imageData) {
        console.log('onSuccess');
        var largeImage = document.getElementById('largeImage');
        largeImage.style.display = 'block';
        largeImage.src = "data:image/jpeg;base64," + imageData;
        setupImage(imageData);
      }

      function onFail(message) {
        console.log('Failed because: ' + message);
      }

      function getMousePos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return {
          x: evt.clientX - rect.left,
          y: evt.clientY - rect.top
        };
      }

      function init(imageObj) {
        console.log('init');

        var padding = 10;
        var mouseDown = false;

        var canvas = document.getElementById('canvas');
        var context = canvas.getContext('2d');
        context.strokeStyle = '#444';
        context.lineWidth = 2;
        context.canvas.width  = window.innerWidth;
        context.canvas.height = window.innerWidth;

        canvas.addEventListener('mousedown', function() {
          mouseDown = true;
        }, false);

        canvas.addEventListener('mouseup', function() {
          mouseDown = false;
        }, false);

        canvas.addEventListener('mousemove', function(evt) {
          console.log('mousemove');

          var mousePos = getMousePos(canvas, evt);
          var color = undefined;

          if (mouseDown && mousePos !== null && mousePos.x > padding && mousePos.x < padding + imageObj.width && mousePos.y > padding && mousePos.y < padding + imageObj.height) {
            var imageData = context.getImageData(padding, padding, imageObj.width, imageObj.width);
            var data = imageData.data;
            var x = mousePos.x - padding;
            var y = mousePos.y - padding;
            var red = data[((imageObj.width * y) + x) * 4];
            var green = data[((imageObj.width * y) + x) * 4 + 1];
            var blue = data[((imageObj.width * y) + x) * 4 + 2];
            var color = 'rgb(' + red + ',' + green + ',' + blue + ')';
            console.log('picked color is ' + color);
            updateColor(red, green, blue);
          }
        }, false);

        context.drawImage(imageObj, padding, padding);
      }

      function updateColor(R, G, B) {
        $scope.hex = rgbToHex(R, G, B);
        console.log($scope.hex);
      }

      function rgbToHex(R, G, B) {
        return toHex(R) + toHex(G) + toHex(B)
      }

      function toHex(n) {
        n = parseInt(n, 10);
        if (isNaN(n)) {
          return "00";
        }
        n = Math.max(0, Math.min(n, 255));
        return "0123456789ABCDEF".charAt((n - n % 16) / 16) + "0123456789ABCDEF".charAt(n % 16);
      }

      function setupImage(_data) {
        console.log('setupImage');

        var imageObj = new Image();
        imageObj.onload = function() {
          init(this);
        };
        imageObj.src = "data:image/jpeg;base64," + _data;
      }

  });

The important part starts after the mousemove event listener. I got the RGB values fine and converted them to Hexadecimal. This all logs fine - the RGB and HEX. But $scope.hex never seems to bind/update the View. Please advise what is going wrong.

Try editing your updateColor() function to something like below.

function updateColor(R, G, B) {
  $scope.hex = rgbToHex(R, G, B);
  console.log($scope.hex);
  $scope.$apply();
}

This should work. The problem that you're probably having is that you're updating the value of hex but probably Angular isn't recognizing the change. $scope.$apply() should force the binding to update hence fixing your problem.

I believe in your case angular is unaware of the change when you use mouse move events because it runs asynchronously. Wrapping the invocation of 'updateColor(red, green, blue);' method in $scope.$apply will help.

So you will have:

$scope.$apply(function () {
    updateColor(red, green, blue);
});

Instead of just:

updateColor(red, green, blue);

You can also use $scope.$apply() without arguments but take a look at here http://jimhoskins.com/2012/12/17/angularjs-and-apply.html they explain why the former method is more preferred.

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.

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