从控制器设置angularjs指令属性

时间:2015-02-11 23:36:38

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

我使用的是Angular Bootstrap typehead指令,可以从HTML配置,如下所示:

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

是否可以设置&#39; typeahead-focus-first&#39;来自ng-controller的属性改为?

2 个答案:

答案 0 :(得分:2)

如果您的控制器范围具有属性

$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)。角度引导程序中的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>

答案 1 :(得分:1)

使用以下表达式从attr评估typeahead属性:

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

因此您应该在范围中设置变量

$scope.typeahead = true;

然后

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

预先输入来源here

编辑: 从评论中可以看出,您希望从控制器编辑行为而无需在dom上编写任何内容。不幸的是,我认为这是不可能的,因为控制该行为的变量在编译时保存在闭包内,并且在链接组件后不可修改。您需要重新编译组件以更改该行为,例如ng-if。

相关问题