2
我最初的目標是創建具有輸入定義的組件,並收集父控制器上的所有內容。我必須使用hacky方法來完成此操作($ rootScope,$ on),但我想知道我的代碼中出錯的地方。這是關於雙向指令和控制器( 「=」)之間的結合如何在指令中使用輸入獲得雙向綁定工作?
我的觀點:
<div ng-app="app" ng-controller="myCtrl">
my input value: {{variable}}
<div my-directive input="variable"></div>
</div>
我控制器/指令
angular.module("app",[])
.controller("myCtrl", function($scope){
$scope.variable = "initial value";
})
.directive("myDirective", function(){
return {
scope: { eggplant: "=input" },
template: "Change the parent value: <input ng-model='eggplant'/>" +
"<br> eggplant: {{eggplant}}"
}
});
無論出於何種原因,這是行不通。我試着在模板上其他一些配置,如...
...
template: "Change the parent value: <input ng-model='{{eggplant}}'/>"
...
...
template: "Change the parent value: <input ng-model='{eggplant}'/>"
...
但最終,我不得不一個控制器(帶$範圍)添加到指令,加NG-改變功能,並且當指令改變時,將其附加到指令控制器$ scope ...但是這不是解決這個問題的正確方法。任何人都可以透露我出錯的地方嗎?
...
.directive("myDirective", function(){
return {
scope: { eggplant: "=input" },
template: "Change the parent value: "+
"<input ng-model='eggplant' ng-change='change(eggplant)'/>",
controller: function($scope){
$scope.change(val){
// I also have a $rootscope hack I can sell you :P
$scope.eggplant = val;
}
}
}
});
感謝您的幫助!
嘿曼尼,謝謝你的迴應。是的,那是我的錯誤。在實際的代碼中,這個錯誤不存在。 –
好的。你能澄清一下你的意思嗎?我沒有看到你有什麼問題和我自己的測試顯示相同:http://plnkr.co/edit/izVo7ojbNUpl9BN8ySIf?p=preview –
那麼這是一個有點平反,但也非常困惑!我知道我做對了!通過「不工作」,我的意思是我可以通過'myCtrl'將指令中的'茄子'設置爲「初始值」,但是當我通過輸入在指令內更改該值時,更改不會反映在myCtrl上。 它現在肯定是一個頭部劃痕。我將不得不看看哪些依賴可能會混淆角色汁液。 –