Search code examples
javascriptangularjsangularjs-directiveangularjs-scope

why is the following Angular 1.6 code not filtering to lowercase this way?


this is my controller code

myApp.controller('MainController',['$scope','$filter',function($scope,$filter){

  $scope.handle = '';
  $scope.lowercasehandle = $filter('lowercase')($scope.handle);

}]);

and this is the html part

<div class="container" ng-controller="MainController">

  <div>
    <label for="">What is your twitter handle?</label>
    <input type="text" ng-model="handle">
  </div>
    <h3>www.twitter.com/{{lowercasehandle}}</h3>

</div>

but the same code works when I make lowercasehandle a function returning the lowercase version of handle. The below example works just fine when called in the html by invoking the function lowercasehandle() in the h3.

myApp.controller('MainController',['$scope','$filter',function($scope,$filter){

$scope.handle = '';
$scope.lowercasehandle = function() {
  return $filter('lowercase')($scope.handle);
};

}]);

So why can't I directly update the value of lowercasehandle in the first case. Why do I need to use a function here? Whatever changes I make in the controller are supposed to show in the view right? So then why I am unable to achieve what I want using the first method?


Solution

  • In the first case,

    $scope.lowercasehandle = $filter('lowercase')($scope.handle);
    

    won't be called when $scope.handle is updated by the user and is assigned only once as. Making it into a function works as it is called on every digest cycle, which then uses the updated value of $scope.handle.