2013-03-15 91 views
12

我有一個指令可以創建一個輸入字段。 我需要將此輸入字段的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 

任何人都可以請解釋一下這個問題?

+0

也可以看看在你的模板,持有該有自己的範圍指令到$ rootScope參考引用$根。請參閱 - http://stackoverflow.com/questions/22216441/what-is-the-difference-between-scope-root-and-rootscope – cchamberlain 2015-03-29 01:49:17

回答

13

我想你想要的是

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

Fiddle

請注意,您將需要注入$rootScope到你的指令:

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

任何想法爲什麼變量值顯示,如果我改變這樣的模板? http://jsfiddle.net/ZavXw/1/ – glasspill 2013-03-15 14:47:34

+0

ng-model =「{{mymodel}}」和placeholder =「{{mymodel}}」有什麼區別? – glasspill 2013-03-15 14:53:31

+0

1.你的小提示:{{}}告訴Angular插入值。由於您的控制器範圍原型繼承自$ rootScope,因此Angular會將'{{mymodel}}'替換爲'search.name'的內插值。 2.您不能在ng模型中使用{{}},因爲Angular不會插值ng模型值。 ng-model值必須是(可指定的)角度表達式。 (同樣,ng-click的值也不能包含{{}} - 它也必須是一個Angular表達式)。佔位符的值可以包含{{}},因爲Angular編譯器會注意到它並對其進行插值。 – 2013-03-15 14:58:39