2016-07-28 68 views
0

我想创建一个指令,基本上包装input。因此,我想将一些属性/参数传递给指令,例如ng-model无法绑定到控制器没有指示'searchBox的控制器

但是我无法正常工作,此刻当我在页面中包含指令时,出现上述错误。

interface ISearchBoxDirectiveScope extends angular.IScope { 
    ngModel: string; 
    placeholderText: string; 
} 

class SearchBoxDirectiveController { 

    static $inject = ["$scope"]; 

    constructor(
     private $scope: ISearchBoxDirectiveScope) { 
     console.log("This doesnt get hit", $scope); 
    } 

    public clearSearchTerm() { 
     console.log("here"); 
     this.$scope.ngModel = ""; 
    } 
} 

class SearchBoxDirective implements angular.IDirective { 

    restrict = "E"; 
    replace = true; 
    scope = { 
     ngModel: "=", 
     placeholderText: "@" 
    }; 
    templateUrl = "app/directives/searchBox/searchBox.template.html"; 
    controller: SearchBoxDirectiveController; 
    controllerAs = "$ctrl"; 
    bindToController = true; 

    public link: (scope: ISearchBoxDirectiveScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes) => void; 

    constructor() { 

     SearchBoxDirective.prototype.link = ($scope: ISearchBoxDirectiveScope, $element: angular.IAugmentedJQuery, attrs: ng.IAttributes) => { 

      console.log("SearchBoxDirective.prototype.link", $scope, attrs); 
     } 
    } 

    static factory(): ng.IDirectiveFactory { 
     const directive =() => new SearchBoxDirective(); 

     directive.$inject = []; 

     return directive; 
    } 
} 

angular 
    .module("app.directives") 
    .directive("searchBox", SearchBoxDirective.factory()); 

和IM调用它像这样

<search-box ng-model="$ctrl.rightSideFilter" placeholder-text="Search Vehicles"></search-box> 

回答

0

我不知道为什么你要访问的NG-模型,因为你是继承了控制器的范围,rightSideFilter应该是提供给您的范围。另外,您可以尝试以下操作。

interface ISearchBoxDirectiveScope extends angular.IScope { 
    rightSideFilter: string; 
    placeholderText: string; 
} 

scope = { 
'rightSideFilter': = '?rightSideFilter', 
///any other 
} 

,并假设,如果这些是你找那么你可以让指令工作孤立的唯一值。

export class SearchBoxDirective implements angular.IDirective { 

    restrict = "E"; 
    replace = true; 
    scope = { 
     ngModel: "=", 
     placeholderText: "@" 
    }; 
    templateUrl = "app/directives/searchBox/searchBox.template.html"; 

和你的HTML语法

<search-box right-side-filter="$ctrl.rightSideFilter" place-holder-text="Search Vehicles"></search-box>