【问题标题】:Set angularjs directive attribute from a controller从控制器设置 angularjs 指令属性
【发布时间】:2015-02-12 08:09:26
【问题描述】:

我正在使用 Angular Bootstrap typehead 指令,可以像这样从 HTML 配置它:

<div ng-controller="search">
  <input typeahead-focus-first="false" />
</div>

是否可以改为从 ng-controller 设置 'typeahead-focus-first' 属性?

【问题讨论】:

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


    【解决方案1】:

    如果你的控制器范围有一个属性

    $scope.typeahead = true;
    

    然后

    <div ng-controller="search">
      <input ng-if="typeahead" typeahead-focus-first="false" />
      <input ng-if="!typeahead" />
    </div>
    

    <div ng-controller="search">
      <input typeahead-focus-first="typeahead" />
    </div>
    

    第二种方法要求您的 typeahead 指令能够解析 typeahead 表达式。有几种方法可以实现这一点(例如,隔离作用域或 $parse)。 angular bootstrap 中的 typeahead 指令会为您执行此操作,因此第二种方法应该可以工作。

    编辑:作为指令

    .directive('search', function() {
        return {
            restrict: 'E',
            template: '<div><input typeahead-focus-first="false" /></div>',
            scope: true,
            controller: function($scope) {
            },
            link: function(scope, element, attrs) {
                //this is where you want to do your DOM manipulation (if any)
            }
        };
    })
    

    用法:

    <search></search>
    

    【讨论】:

    • 感谢您的意见。但是我一直在寻找一个可以从 JS 设置并且在 HTML 中根本没有提到的解决方案;因为我有几个打字头,而且都有这个设置,所以每次定义它都是混乱的。
    • 作为 Angular 的一般最佳实践,您不应该在控制器中操作 DOM。您正在寻找的选项可能是创建自定义指令。
    【解决方案2】:

    typeahead 属性是从 attr 使用以下表达式计算的:

    var focusFirst = originalScope.$eval(attrs.typeaheadFocusFirst) !== false;
    

    所以你应该在你的范围内设置一个变量

    $scope.typeahead = true;
    

    然后

    <div ng-controller="search">
        <input typeahead-focus-first="{{typeahead}}" />
    </div>
    

    预输入源here

    编辑: 正如从 cmets 中出现的那样,您似乎想从控制器编辑行为而不在 dom 上写任何东西。不幸的是,我认为这是不可能的,因为控制该行为的变量在编译时保存在闭包中,并且在链接组件后不可修改。您需要重新编译组件以更改该行为,例如使用 ng-if。

    【讨论】:

    • 我认为 $eval 不适用于 {{}}。 scope.$eval 等价于 $parse(expression)(scope)。
    • 它有效,但仅在第一个链接阶段,typeahead 将根据编译组件时的范围值设置为 true 或 false。它不会是双向绑定的。
    猜你喜欢
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    • 2013-03-15
    • 2023-03-23
    • 1970-01-01
    • 2014-04-07
    相关资源
    最近更新 更多