AngularJs : Custom Directive Scope is Undefined

angularjs angularjs-directive

59 观看

1回复

23 作者的声誉

I want to put the value from the other controller to my custom directive , but the value in the watch function in the directive is coming undefined .Here is my code :

directive code :

function associates($templateCache,$compile) {
        var directive = {};
        directive.restrict = 'E';
        directive.controller = 'associatesTypeaheadController';
        directive.controllerAs = 'ctrlTA';
        directive.template = $templateCache.get('typeahead.template.html');
        directive.scope= {
            "options": '='
        };
        directive.link=link;

        return directive;
    }
     function link(scope, element, attrs) {
         scope.$watch('options.reload', function(data){
                console.log(data); //Still undefined
            });
    }

Controller :

employeeDetails.opts = {
      "reload": false,
      "refresh": false
    };

    employeeDetails.reload = function () {
      employeeDetails.opts.reload = true;
      console.log('there');
      return employeeDetails.opts.reload;
    };
    employeeDetails.reload();
作者: Amit Ranjan 的来源 发布者: 2017 年 9 月 15 日

回应 1


0

23 作者的声誉

After lot's of struggle, i found the solution :

Directive To share between two controller:

directive.restrict = 'E';
    directive.controller = 'associatesTypeaheadController';
    directive.controllerAs = 'ctrlTA';
    directive.template = $templateCache.get('typeahead.template.html');
    directive.compile = function (element, attributes) {
      var linkfunction = function ($scope) {
        if ($scope.employeeDetails && $scope.employeeDetails.hint) {
          $scope.hint = $scope.employeeDetails.hint;
        }
        if ($scope.ctrl && $scope.ctrl.hint) {
          $scope.hint = $scope.ctrl.hint;
        }

      };
      return linkfunction;

    };
    return directive;
  }

Controller A:

employeeDetails.scope = $scope;
employeeDetails.hint = "Reports To";

Controller A HTML Scope :

<associates></associates>

Directive HTML :

<md-autocomplete 
        flex id="associate-typehead"
        md-input-name='autocompleteField'
        md-input-minlength='2' md-input-maxlength='50'
        md-no-cache='ctrlTA.noCache'
        md-selected-item='ctrlTA.selectedItem'
        md-search-text='ctrlTA.searchText'
        ng-model-options='{debounce : 1000}'
        md-floating-label={{hint}}
        md-items='item in ctrlTA.querySearch(ctrlTA.searchText)'
        md-item-text='item.username'  >
    <md-item-template>
        <span md-highlight-text='ctrlTA.searchText'>{{item.lastName + ', ' + item.firstName + ' (' + item.username + ')'}}</span>
    </md-item-template>
</md-autocomplete>
作者: Amit Ranjan 发布者: 2017 年 9 月 15 日
32x32