Я хочу преобразовать переменную с областью видимости, например обрезать переданную строку. но он всегда показывает, как прошел.

Вот мой пример кода,

export function testDirective() {
    return {
        restrict: 'E',
        template: `<a>{{vm.testText}}</a>`,
        scope: {
            testText: '@'
        },
        controller: TestController,
        controllerAs: 'vm',
        bindToController: true
    }
}

export class TestController {
    testText: string;

    constructor(private $scope: angular.IScope) {
        // when getting variable, I need to transform the value
        $scope.$watch( () => this.testText, (newVal: string) => {
            this.testText = newVal.trim() + ' Edited'; // this doesn't affact
        });
    }
}

Почему этот код не работает?

Чтобы заставить его работать, я добавил дополнительную переменную (trimmedText), но я не думаю, что это правильный подход,

export function testDirective() {
    return {
        restrict: 'E',
        template: `<a>{{vm.trimmedText}}</a>`,
        scope: {
            testText: '@'
        },
        controller: TestController,
        controllerAs: 'vm',
        bindToController: true
    }
}

export class TestController {
    testText: string;
    trimmedText: string;

    constructor(private $scope: angular.IScope) {
        // when getting variable, I need to transform the value
        $scope.$watch( () => this.testText, (newVal: string) => {
            this.trimmedText = newVal.trim() + ' Edited'; // it works
        });
    }
}

Пожалуйста, посоветуй мне…

0
Expert wanna be 6 Сен 2016 в 12:47

3 ответа

Лучший ответ

@Expert хочет быть, использование знака = в изолированной области определения директивы устанавливает двустороннюю привязку данных внутри директивы.

Просмотрите приведенный ниже фрагмент кода, здесь ссылку jsfiddle. Вы можете найти дополнительную информацию о различных типах привязки данных в директивах здесь

HTML

<div ng-app="demo">
  <div ng-controller="DefaultController as ctrl">
    <custom-directive test-text="ctrl.text"></custom-directive>
  </div>
</div>

Код на Angular

angular
  .module('demo', [])
  .controller('DefaultController', DefaultController)
  .controller('CustomDirectiveController', CustomDirectiveController)
  .directive('customDirective', customDirective);

  function DefaultController() {
    var vm = this;
    vm.text = 'Hello, ';
  }

  function customDirective() {
    var directive = {
      restrict: 'E',
      template: `<a href="#">{{vm.testText}}</a>`,
      scope: {
        testText: '='
      },
      controller: CustomDirectiveController,
      controllerAs: 'vm',
      bindToController: true
    };

    return directive;
  }

  function CustomDirectiveController() {
    var vm = this;
    // transforming/updating the value here
    vm.testText = vm.testText + 'World!';
  }
1
Community 23 Май 2017 в 10:33
$scope.$watch( () => this.testText, // <-- use this.textText here
0
Makarov Sergey 6 Сен 2016 в 09:51

'@' не является правильным связыванием, если вы хотите его изменить - используйте '='. Но использование дополнительной переменной - действительно правильный подход.

Еще один хороший способ простого преобразования - использовать фильтр.

0
Petr Averyanov 6 Сен 2016 в 10:44