【问题标题】:Cannot bind to controller without directive 'searchBox's controller没有指令'searchBox'控制器无法绑定到控制器
【发布时间】:2016-07-28 14:43:44
【问题描述】:

我正在尝试创建一个基本上包含input 的指令。因此,我想将一些属性/参数传递给指令,例如ng-model

但是,当我在页面中包含指令时,我遇到了上述错误。

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

我这样称呼它

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

【问题讨论】:

    标签: angularjs angularjs-directive typescript


    【解决方案1】:

    我不确定你为什么要访问 ng-model,因为你是从控制器继承作用域的,所以你应该可以在作用域上使用 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-12
      • 2015-04-05
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-15
      相关资源
      最近更新 更多