【问题标题】:AngularJS evaluate $rootScope variable in directive templateAngularJS 在指令模板中评估 $rootScope 变量
【发布时间】:2013-03-15 13:55:32
【问题描述】:

我有一个创建输入字段的指令。 我需要将此输入字段的 ng-model 属性设置为 $rootScope 的值 多变的。 这背后的原因是我希望输入字段在布局中,并根据加载的页面绑定到不同的模型。 我以为我会在每个控制器中设置这个全局变量并在指令中访问它。

ATM 变量是硬编码的

App.run(function($rootScope){
    $rootScope.mymodel = 'search.name';
})

还有指令

Directives.directive('inputFilter', function(){
    return{
        restrict: 'E',
        replace:true,
        controller: function($scope, $rootScope){
            console.log($scope.mymodel);
            console.log($rootScope.mymodel)

        },
        template: '<input class="filter" type="text" ng-model="mymodel" placeholder="Nach filtern">'
    }

});

它被渲染为

<input class="filter ng-pristine ng-valid" type="text" ng-model="mymodel" placeholder="Filter">

输入字段中的文本是 mymodel 变量的值。 console.log 显示

search.name
search.name  

谁能解释一下这个问题?

【问题讨论】:

标签: angularjs angularjs-directive angularjs-scope


【解决方案1】:

我认为你想要的是

template: '<input class="filter" type="text" ng-model="' 
  + $rootScope.mymodel + '" placeholder="Nach filtern">'

Fiddle.

请注意,您需要将$rootScope 注入到您的指令中:

Directives.directive('inputFilter', function($rootScope) {

【讨论】:

  • 知道如果我像这样更改模板,为什么会显示变量值吗? jsfiddle.net/ZavXw/1
  • ng-model="{{mymodel}}" 和 placeholder="{{mymodel}}" 有什么区别
  • 1.您的小提琴:{{}} 告诉 Angular 插入值。由于您的控制器范围原型继承自 $rootScope,Angular 将 {{mymodel}} 替换为 search.name 的插值。 2. 你不能在 ng-model 中使用 {{}},因为 Angular 不会插入 ng-model 值。 ng-model 值必须是(可分配的)角度表达式。 (同样,ng-click 的值也不能包含 {{}}——它也必须是 Angular 表达式)。 placeholder 的值可以包含 {{}},因为 Angular 编译器会注意到它并对其进行插值。
  • @glasspill,所以简单的规则是:如果 Angular 文档说某些东西需要 Angular 表达式,我们不能在那里使用 {{}}。在我们的 HTML(和模板)中,我们可以使用 {{}}(只要它不是 Angular 想要看到 Angular 表达式的地方)并且 Angular 会执行插值魔法。
  • 谢谢,这让我非常沮丧和困惑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 2016-05-30
  • 1970-01-01
相关资源
最近更新 更多