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

时间:2013-03-15 13:55:32

标签: angularjs angularjs-directive angularjs-scope

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

有谁能请对这个问题有所了解?

1 个答案:

答案 0 :(得分:13)

我认为你想要的是

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

Fiddle

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

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