2015-05-17 3 views
0

Вот моя директива, это просто задача Locale время Дата Строка:angularjs директива 2 способ привязки не работает

 .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); 
      } 
      } 
    }; 

}]) 

Использование в 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> 

Когда я загружаю объект «профиль» от JSON все в порядке проблема заключается в том, что я меняю «note.Created» с контроллера - директива кажется неработоспособной (другие члены примечания обновляются нормально):

В contr Oller:

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 
      } 
     ); 

Например, здесь область перед "updateProfileRemark":

scope from ng-inspector

и после того, как:

scope from ng-inspector

Почему 2 способ привязки не работает? Спасибо.

ответ

1

Ссылка выполняется только один раз. Если вы хотите установить двустороннюю привязку между $ scope.timeLocal и $ scope.time, настройте $ 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); 

     } 
    });