小编典典

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

angularjs

我有一个创建输入字段的指令。我需要将此输入字段的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

任何人都可以在这个问题上阐明一下吗?


阅读 248

收藏
2020-07-04

共1个答案

小编典典

我想你想要的是

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

小提琴

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

Directives.directive('inputFilter', function($rootScope) {
2020-07-04