2013-08-21 58 views
0

我一直在嘗試整個下午解決以下問題:我組成了一個顯示搜索表單的指令。 searchterm的模型在控制器中定義並完美地與指令通信。但是:當我將這個指令放在一個Angular模板中時,這個指令是在DOM準備好之後加載的,它只是進入指令的一種方式,而不是返回。雙向綁定的指令是在模板內部不起作用

<body ng-app="myApp"> 
<div ng-controller="NewEditCtrl"> 

    <script type="text/ng-template" id="/tab-content.html"> 
    <!-- First position for the directive: The way back from the directive to here does not work --> 
    <!-- Uncomment to test and show the console output ! --> 

    <!-- <span mediasearch term="searchterm" enter="sendForm(e)" action="refreshAvailable()"></span> --> 
    </script> 
     <!-- Second position: Here the way back from the directive works perfectly --> 
     <span mediasearch term="searchterm" enter="sendForm(e)" action="refreshAvailable()"></span>  
    <div id="tab-content" ng-include src="tabcontent"></div> 

</div> 

我把例如在工作小提琴:http://jsfiddle.net/RCaCM/2/請參見注釋。

我想這是一個範圍問題,但我不明白$ apply或$ compile的意思。

在此先感謝您的幫助。 XL

回答

0

你說得對,這是一個範圍問題:用ng-include角度創建一個子範圍。因此,當您更改父作用域中的屬性時,它也會更改該子項中的值,但不會在另一側進行更改。 如果你想要這兩個鏈接,你應該你的中間服務

另一種方式可能是發佈變化從您的指令到父範圍,並在主範圍(或在根目錄)聆聽它:

http://jsfiddle.net/RCaCM/3/

+0

感謝,塞巴斯蒂安,對於提供的解決方案。我選擇了Chandermani,但我想了解服務的使用情況。 – dryhead

1

正如@Sebastien指出的那樣,ng-include創建一個子範圍。你必須綁定任何對象,它會工作,看到我更新的小提琴。

http://jsfiddle.net/cmyworld/JC28H/

而不是使用searchterm的,使用類似

$scope.searchterm={value:''} 
+0

很好,Chandermani,爲我開箱即用!爲什麼它以這種方式處理對象而不是範圍變量? – dryhead

+1

是的,我忘記了!如果我記得很清楚(我是angular和javascript的新手),如果它是一個變量,angular會創建一個副本,但如果它是一個對象,則不會創建副本 –

+1

我相信javascript不是AngularJS。它只針對基本類型和字符串進行。如布爾值,整數等 – Chandermani