AngularJS 评估指令模板中的 $rootScope 变量 [英] AngularJS evaluate $rootScope variable in directive template

查看:23
本文介绍了AngularJS 评估指令模板中的 $rootScope 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a directive that creates an input field. I need to set the ng-model attribute of this input field to the value of a $rootScope variable. The reason behind this is that I want the input field to be in the layout, and bind to different models depending on what page is loaded. I thought I'd set this global variable in each controller and access it in the Directive.

ATM 变量是硬编码的

ATM the variable is hard coded

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 显示

and the text inside the input field is the value of mymodel variable. The console.log shows

search.name
search.name  

有人能解释一下这个问题吗?

Could anyone please shed some light on this issue?

推荐答案

我认为你想要的是

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

小提琴.

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

Note that you will need to inject $rootScope into your directive:

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

这篇关于AngularJS 评估指令模板中的 $rootScope 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆