AngularJs:自定义指令范围未定义

时间:2017-09-15 06:14:54

标签: angularjs angularjs-directive

我想将来自其他控制器的值放到我的自定义指令中,但指令中watch函数中的值未定义。这是我的代码:

指令代码:

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

控制器:

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

    employeeDetails.reload = function () {
      employeeDetails.opts.reload = true;
      console.log('there');
      return employeeDetails.opts.reload;
    };
    employeeDetails.reload();

1 个答案:

答案 0 :(得分:0)

经过多次努力,我找到了解决方案:

指令在两个控制器之间共享:

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

控制器A:

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

控制器A HTML范围:

<associates></associates>

指令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>