Faizan Ali
Faizan Ali

Reputation: 330

Can't update variable value inside function angularjs

Hello developers please help, updating value dynamically working perfect inside angularjs controller which is passing in html tag. But when I use scope variable inside function (within controller).

Working perfect when updating value outside function:

var app = angular.module('previewApp', []);

app.controller('previewCtrl', function ($scope) {
  var $ = jQuery;
  var targetValue = 0;
  $scope.w = targetValue;
});

passing to html span tag:

<span style="width:{{w}}px;height:{{h}}px; background-color: white" class="item-inner">

But I am getting value using jQuery whenever input event trigger value is not updating inside function dynamically, in console value is updating perfectly (console.log('Width ' + targetValue);) but not in html tag:

function onChangeWidth(event) {
  if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
    isProcess = false;
  }
  const targetValue = $(this).closest('.gfield').find('input').val();
  // $scope.width = ;
  $scope.w = function () {
    return targetValue;
  };

  $scope.docPPIWidth = ppi * +targetValue;
  console.log('Width ' + targetValue);
  $scope.w = targetValue; //updating w didn't work inside function
}

function onChangeHeight(event) {
  const targetValueH = $(this).closest('.gfield').find('input').val();
  if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
    var isProcess = false;
  }
  $scope.docPPIHeight = ppi * targetValueH;
  console.log('Height ' + targetValueH);
}
$('.width_check input').on('change click', onChangeWidth);
$('.height_check input').on('change click', onChangeHeight);

Upvotes: 2

Views: 656

Answers (1)

dim0_0n
dim0_0n

Reputation: 2504

My first recommendation for you is to start thinking about how to prevent mixing JQuery and AngularJS, because eventually you will end up with "bug apocalypse". I think what happens in your case is that Angular is not aware about JQuery triggered an event, so the digest loop is not triggered automatically. Again, this solution can help you in that particular situation, but it is really not a good practice:

$scope.w = targetValue;
$scope.$digest();

After you change scope variable, let Angular know that it has to trigger digest loop to refresh view data by adding $scope.$digest(). This function will check only this component and its children scope data. In case if you need to check entire app, use $rootScope.$digest() (very poor decision from the performance standpoint).

Upvotes: 2

Related Questions