AngularJS 在指令模板中评估 $rootScope 变量

标签 angularjs angularjs-directive angularjs-scope

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

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  

任何人都可以对这个问题有所了解吗?

最佳答案

我想你想要的是

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

Fiddle .

请注意,您需要注入(inject) $rootScope进入你的指令:
Directives.directive('inputFilter', function($rootScope) {

关于AngularJS 在指令模板中评估 $rootScope 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15434264/

相关文章:

javascript - AngularJS 对象在 Controller 方法中丢失值

Django Rest Framework/Angular JS 预检选项

javascript - 在 Angular 中将数据附加到 $scope 的不同方法

javascript - Angular UI 网格 : render image if it exist on a separate server otherwise set a default image

angularjs - 在 Mocha 测试套件中触发 AngularJS 指令上的点击事件

javascript - 为什么模型不更新 View ?

javascript - 将子级添加到 Angular UI Tree 上的任何父级会将其推送到每个父级

angularjs - ng-repeat 和 ng-switch 不适用于同一元素

javascript - 使用 Angular 格式化程序/解析器

javascript - 从 .then() 内更新 ng-show