0

В ходе экспериментов с angular обнаружилась странная проблема с transclude. Такое ощущение что элемент который будет включен в директиву через трасклюд где-то кешируется.

В моем примере получается что элемент input, который определенным образом включается в элемент span, при использовании ng-repeat всегда один и тот же. В результате получается что он перемещается вниз по списку при каждом его включении.

код примера, и он же на plunker

// Code goes here
angular.module('app', [])
  .controller('Ctrl', function($scope) {
    $scope.items = [{
      id: 1
    }, {
      id: 2
    }, {
      id: 3
    }, ]; 
    $scope.$on('remove', function(event, item) {
      var index = $scope.items.indexOf(item);
      $scope.items.splice(index, 1);
    });
  })
  .directive('closable', function(){
    return {
      restrict: 'E',
      require: 'ngModel',
      transclude: true,
      replace: true,
      template: '<span> <a ng-click="close()">x</a></span>',
      link: function(scope, elem, attrs, ngModel, transcludeFn){
        scope.close = function(){
          scope.$emit('remove', ngModel.$modelValue);
        }
        
        var transclusion = transcludeFn(scope);
        console.log(transclusion, elem.find('span'));
        elem.prepend(transclusion);
      }
    }
  })
  .directive('test', function() {
    return {
      restrict: 'E',
      require: 'ngModel',
      template: '<closable ng-model="item"><input type="text" ng-model="id"></closable>',
      scope: {},
      link: function(scope, elem, attrs, ngModel) {
        ngModel.$formatters.push(function(modelValue) {
          console.log('$formatters', modelValue);
          return {
            id: modelValue.id + 1
          };
        });

        ngModel.$parsers.push(function(viewValue) {
          ngModel.$modelValue.id = viewValue.id - 1;
          console.log('$parsers', ngModel.$modelValue, viewValue);
          return ngModel.$modelValue;
        });

        ngModel.$render = function() {
          scope.id = ngModel.$viewValue.id;
          scope.item = ngModel.$modelValue;
        }

        scope.$watch('id', function() {
          ngModel.$setViewValue({
            id: scope.id
          });
        });
      }
    };
  })
<!DOCTYPE html>
<html ng-app="app">

  <head>
    <link data-require="[email protected]" data-semver="3.3.2" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script data-require="angular.js@*" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="Ctrl">
    <pre>{{ items|json }}</pre>
    <ul class="list-unstyled">
      <li ng-repeat="item in items">
        <test ng-model="item"></test>
      </li>
    </ul>
  </body>

</html>

2 ответа 2

1

Да, интересное поведение, и, думаю, вы правы - инпут один и тот же. Для решения могу предложить два варианта: 1) изменить код в функции link

transcludeFn(scope, function(clone){
  elem.prepend(clone);
});

2) Вы можете добавить директиву ngTransclude в шаблон, т.е.template: <span><span ng-transclude></span><a ng-click="close()">x</a></span>

1
  • ng-transclude помогает, правда чтобы все работало нужно в input изменить ng-model="id" на ng-model="$parent.id" еще как ни странно вот такой способ с пустой функцией тоже заработал :) transcludeFn(scope, function(){});
    – beh
    29 апр 2015 в 20:11
0
template: '<span> <a ng-click="close()">x</a></span>',

var transclusion = transcludeFn(scope);
console.log(transclusion, elem.find('span'));
elem.prepend(transclusion);

А чем не угодил нормальный вариант безо всяких фокусов с ручным добавлением?

template: '<span><span ng-transclude></span><a ng-click="close()">x</a></span>',

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.