Angular 1.x - получить значение директивы из контроллера и вернуть его в родительскую область - PullRequest
0 голосов
/ 08 мая 2018

Я не могу получить значение переменной из директивы, чтобы использовать ее обратно в контроллере.Мне не нужно привязывать значение к представлению.Все, что мне нужно, это установить 'cleanInputValue' из директивы в $ scope.keywords в Controller.

Вот моя директива и контроллер -

HTML с автозаполнением md для поля ключевых слов - поле поиска.

 <form id="searchbox" ng-controller="navsearchController as sc" title="Search this site" layout="row">
          <md-autocomplete
            md-no-cache="true"
            md-selected-item="sc.currentKeyword"
            md-search-text="keywords"
            md-items="item in querySearch(keywords)"
            md-item-text="item.display"
            md-min-length="3"
            md-input-name="search"
            md-input-id="search-nav"
            md-clear-button="false"
            placeholder="Search"
            md-dropdown-position="bottom"
            flex>
            <md-item-template>
              <span md-highlight-text="keywords" md-highlight-flags="gi">{{item.display}}</span>
            </md-item-template>
          </md-autocomplete>
          <div class="search-button" flex="none">
            <button type="submit" ng-click="sc.search()" title="Search" tabindex="0">GO</button>
          </div>
        </form>

Директива:

.directive('test', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
       scope: {
            text: '@text'
        },
        link:function(scope, element, attrs, modelCtrl){
          modelCtrl.$parsers.push(function(inputValue) {
            if (inputValue === undefined){
            return '';
            }
            var cleanInputValue = inputValue.replace(/[^\w\s\-\"]/gi, '');

            if (cleanInputValue != inputValue) {
            modelCtrl.$setViewValue(cleanInputValue);
            modelCtrl.$render();
          }
          return cleanInputValue;
          });
            //console.log(scope.text);
        }
    };
})

Контроллер:

.controller('navsearchController', function($timeout, $element, $compile, $scope, $rootScope, $http, $location, DataService, $routeParams, $filter, $route){
    var _this = this;

    $timeout(function () {
       var myAutoCompleteInput = 
        angular.element($element[0].querySelector('#search-nav'));
        myAutoCompleteInput.attr("test", "test");
        //myAutoCompleteInput.attr("text", "blah");
         console.log($scope.keywords);

         $compile(myAutoCompleteInput)($scope);
        });

      _this.search = function(){           

       xyzStorage.set('currentKeyword', $scope.keywords);
       $scope.keywords = $filter('removeSpecialChars')($scope.keywords);
       $location.path('/xyz/search/' + $scope.keywords);

      $location.url($location.path());

      $location.search({
        range: xyzStorage.get('itemPerPage'),
      })
      $route.reload();
    };

})

1 Ответ

0 голосов
/ 08 мая 2018

Что вы действительно хотите сделать, это связать значение из вашего контроллера с вашей директивой. Не думайте, что это «возврат» значения из вашей директивы. Давайте взглянем.

.directive('test', function () {
    return {
        require: 'ngModel',
        restrict: 'A',
       scope: {
            text: '@text',
            cleanInputValue: '=testTextClean' // Adding a new TWO WAY binding here!
        },
        link:function(scope, element, attrs, modelCtrl){
          modelCtrl.$parsers.push(function(inputValue) {
            if (inputValue === undefined){
            return; // exit the function and don't assign, ok
            }
            // Now we use scope
            scope.cleanInputValue = inputValue.replace(/[^\w\s\-\"]/gi, '');

            if (scope.cleanInputValue != inputValue) {
              modelCtrl.$setViewValue(scope.cleanInputValue);
              modelCtrl.$render();
            }
          // no longer need a return 
          });
        }
    };
})

В вашем контроллере вы получаете доступ к элементу ввода в компоненте md-autocomplete

.controller('navsearchController', function($timeout, $element, $compile, $scope, $rootScope, $http, $location, DataService, $routeParams, $filter, $route){
    var _this = this;

    $timeout(function () {
       var myAutoCompleteInput = 
        angular.element($element[0].querySelector('#search-nav'));
        myAutoCompleteInput.attr("test", "test");
        myAutoCompleteInput.attr("test-text-clean", "sc.keywords");
         console.log($scope.keywords);

         $compile(myAutoCompleteInput)($scope);
        });

      _this.search = function(){           

       xyzStorage.set('currentKeyword', $scope.keywords);
       $scope.keywords = $filter('removeSpecialChars')($scope.keywords);
       $location.path('/xyz/search/' + $scope.keywords);

      $location.url($location.path());

      $location.search({
        range: xyzStorage.get('itemPerPage'),
      })
      $route.reload();
    };

})

Теперь в вашем контроллере значение в $ scope.keywords всегда будет иметь обновленное значение, установленное из вашей директивы.

...