Ilan
Ilan

Reputation: 383

angularjs directive 2 way binding not working

Here is my directive, it's simple task is to Locale Date String time:

     .directive('localeDateString',['$window', function ($window) {
     return {
         restrict: 'E',
         replace: true,
         scope: {
             time: '='
              },
         template: '<span>{{timeLocal}}</span>',
         link: function ($scope, $element) {
             if ($scope.time != null) {
                 profileDate = new Date($scope.time);
                 var cultureCode = $window.ApiData.CultureCode;
                 $scope.timeLocal = profileDate.toLocaleDateString(cultureCode);
             }
            }
     };

 }])

Usage in HTML:

  <li ng-repeat="note in profile.AccountProfile.Notes" class="noteItem">
      <locale-date-string time="note.Created" ></locale-date-string>
      <span>{{note.UserName}}</span>
      <!-- other stuff .. -->      
  </li>

When I'm loading the object "profile" from JSON everything is OK the problem is when i change "note.Created" from controller - the directive seem not to work(other members of Note are updating ok):

In the controller:

 DataService.updateProfileRemark(objRemark)
          .then(function (response) {
              // all is ok;  
              var profileIndex = $scope.ProfileList.indexOf(profile);
              var noteIndex = $scope.ProfileList[profileIndex].AccountProfile.Notes.indexOf(note);
              // this is working:
              $scope.ProfileList[profileIndex].AccountProfile.Notes[noteIndex].UserName = objRemark.UserName;
              // this is not:
              $scope.ProfileList[profileIndex].AccountProfile.Notes[noteIndex].Created = Date.now();


          },
          function (errResponse) {
             // handle err
          }
        );

For example, here is the scope before "updateProfileRemark":

scope from ng-inspector

and after:

scope from ng-inspector

Why the 2 way binding not working? Thanks.

Upvotes: 0

Views: 53

Answers (1)

Michael Kang
Michael Kang

Reputation: 52867

link is only executed once. If you want to setup two-way binding between $scope.timeLocal and $scope.time, setup a $watch:

link: function ($scope, $element) {
    $scope.$watch('time', function(newTime) {
         if (newTime != null) {
             var profileDate = new Date(newTime);
             var cultureCode = $window.ApiData.CultureCode;
             $scope.timeLocal = profileDate.toLocaleDateString(cultureCode);

         }
    });

Upvotes: 1

Related Questions