【问题标题】:Angular UI Typeahead custom directive - model not updated on selectAngular UI Typeahead 自定义指令 - 模型未在选择时更新
【发布时间】:2018-02-09 01:34:25
【问题描述】:

我制作了在内部使用 Angular UI typeahead 指令的自定义指令,但没有按预期工作。在我的指令模型中,选择时没有更新。有人帮忙吗?为了测试,我使用了静态数组而不是 http 服务。笨蛋HERE.

.directive('httpDictionary', ['$compile', function($compile){
    return {
        scope: {
        },
        restrict: 'A',
        controllerAs: "dm",
        controller: ['$scope', '$http', 'ARRAY', function($scope, $http, ARRAY){
           var dm = this;
           dm.dict = function(val){
            return ARRAY; // for testing only
            // return $http.get($scope.dictionaryUrl, { ...
           } 
        }],
        link: function(scope, element, attributes, ngModel) {
            scope.dictionaryUrl = attributes.httpDictionary;
            element.removeAttr('http-dictionary'); // avoid loop
            element.attr('uib-typeahead', 'd for d in dm.dict($viewValue)');
            $compile(element)(scope);
        }
    };    
}])

【问题讨论】:

    标签: angularjs angularjs-directive angular-ui-bootstrap


    【解决方案1】:

    我使这个工作如下所示。 Plunker 代码here。我在指令范围内绑定了 ngModel 并使用了typeahead-on-select 回调函数。我不认为这是优雅的,但有效。我一直在考虑使用$watch,但没有成功。如果你有更好的灵魂,我会很高兴。

    .directive('httpDictionary', ['$compile', function($compile){
        return {
            scope: {
              ngModel: '='
            },
            restrict: 'A',
            controllerAs: "dm",
            controller: ['$scope', '$http', 'ARRAY', function($scope, $http, ARRAY){
               var dm = this;
               dm.dict = function(val){
                return ARRAY; // for testing only
                // return $http.get($scope.dictionaryUrl, { ...
               } 
               dm.select = function($model) {
                  $scope.ngModel = $model;
               }           
            }],
            link: function(scope, element, attributes, ngModel) {
                scope.dictionaryUrl = attributes.httpDictionary;
                element.removeAttr('http-dictionary'); // avoid loop
                element.attr('uib-typeahead', 'd for d in dm.dict($viewValue)');
                element.attr('typeahead-on-select','dm.select($model)');
                element = $compile(element)(scope);
            }
        };    
    }])
    

    【讨论】:

      【解决方案2】:

      为了帮助绑定到模型,我通常使用uib-typeahead 设置typeahead-on-select。这样,您可以在设置新模型时检查或执行一些额外的代码。

      我对你找到的 here 代码做了一个小程序,但做了一些小的调整:

      • 我将输入文本字段隔离到自己的视图中,以便将功能与父视图分开。

      • 我将test 模型传递给指令的范围属性,然后将其绑定到指令控制器(使用bindToController 属性),所以如果您需要test 模型与父控制器通信未来,你可以这样做。

      希望这会有所帮助。

      【讨论】:

      • 您的代码工作正常,但该形式的指令 (restrict:'E') 不能与其他指令一起使用。我需要它作为属性。
      猜你喜欢
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多