【问题标题】:ctrl in undefined in angular directivectrl in undefined in angular 指令
【发布时间】:2019-09-21 02:09:52
【问题描述】:

我尝试创建一个显示完整国家/地区列表的 Angular 指令,我可以在我的应用程序中重复使用这些指令。

列表显示出来了,我可以根据html中的ng-model预填充列表中的值,但是无法从列表中获取选中的值。当我尝试执行 ctrl.$setViewValue 来更新主范围时出现错误。

这是我目前拥有的代码。

指令

    prismanoteApp.directive('countryList', function() {
    return {
        restrict: 'E',
        scope: {
            ngModel: '=',
            required: '=ngRequired',
            label: '@label'
        },
        templateUrl: '../views/directives/country-list.html',

        link : function(scope, element, attrs, ctrl){
            console.log("scope", scope, "ctrl",ctrl); //Here is ctrl undefined
            scope.countries = [{name: "Netherlands", code: "NL"}] //whole list of countries

            if(scope.ngModel){
                var index = _.findIndex(scope.countries, {code: scope.ngModel.toUpperCase()})
                if(index >= 0){
                    scope.country = scope.countries[index];
                }
            } 

            scope.updateCountry = function(selected){
                console.log("SELECTED", selected.code);

                ctrl.$setViewValue(selected);
                scope.country = selected
            }
        }
    };
});

指令 HTML

<div class="div">
    <label for="{{label}}">{{:: "TEXT_COUNTRY" | translate}} id="{{label}}" name="{{label}}"</label>
    <ui-select ng-model="country" ng-change="updateCountry($select.selected)" theme="bootstrap">
        <ui-select-match placeholder="{{:: 'SELECT_OR_SEARCH_COUNTRY' | translate}}">{{$select.selected.name}}</ui-select-match>
        <ui-select-choices repeat="country in countries | filter: $select.search">
            <div ng-bind-html="country.name | highlight: $select.search">
        </ui-select-choices>
     </ui-select>
</div>

HTML

<div class="form-group">
    <div class="col-md-12 no-padding-left">
        <country-list ng-required="false" label="shopCountry" ng-change="getAddressInfo()" ng-model="currentShop.address.country"></country-list>
    </div>
</div>

由于 ctrl 未定义,我无法调用 $setViewValue() 函数,但我怎样才能让它工作呢?

我已经尝试了几个选项,范围变量限制为“A”,在指令中需要。

【问题讨论】:

  • 指令定义中需要require: 'ngModel'。见this帖子

标签: angularjs


【解决方案1】:

它是undefined,因为没有指定控制器。它不存在或未在模块上注册。 (从 1.3+ 起不允许全局控制器 see this SO answer.) 如果它在另一个模块上注册,则必须将该模块作为依赖项添加到当前模块。

您需要在您的模块上定义一个控制器并在您的模板中使用ng-controller 或在您的指令中使用require 指定它以从父节点请求控制器:

return { restrict: 'E', require: 'someController' scope: { ...

AngularJS docs for link function:

控制器 [...] 如果没有,则未定义。

【讨论】:

    猜你喜欢
    • 2014-06-29
    • 2023-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2022-01-16
    相关资源
    最近更新 更多