我已經看到這個問題問幾次了。但是無法以正確的方式在這些答案中實施解決方案。我是Angular的新手,嘗試使用Observe或監視將插入表達式傳遞到自定義指令以獲取單向綁定。要將插入的表達式傳遞到角度指令
我不確定什麼是使用$ observe獲得此行爲的正確方法。
我試過了。
attr.$observe('oneway', function (attributeValue) {
scope.oneway = scope.$parent.$eval(attributeValue);
});
但發現以下問題
在屬性值不得包含{{}} $其他的eval將 失敗。
<mydir oneway=Prop1></mydir>
將工作`<mydir oneway={{Prop1}}></mydir>` fails But this will fail my entire objective to have a one-way binding between directive and parent
即使我有指令內的表達,觀察$得到 只發射一次。更改{{Prop1}}不會觸發觀察 函數。
- 我試過用$ watch代替$ observe。但仍然面臨同樣的問題
使用observe \ watch獲取控制器和指令之間的單向綁定的正確方法是什麼?
繼模板(HtmlPage1.html)的完整代碼
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>TestView</title>
<script src="~/Scripts/angular.js"></script>
<script>
function customdir1() {
var directiveDefinitionObject = {};
directiveDefinitionObject.templateUrl = "/CustomControl/HtmlPage1.html";
directiveDefinitionObject.scope = { oneway: "@@oneway" };
directiveDefinitionObject.link = function (scope, element, attr, ctrl) {
attr.$observe('oneway', function (attributeValue) {
scope.oneway = scope.$parent.$eval("Prop1");
});
}
return directiveDefinitionObject;
}
var app = angular.module("myapp", []).controller("myCont", function ($scope) {
$scope.Prop1 = "TestProp1Text";
}).directive("mydir", customdir1);
</script>
</head>
<body ng-app="myapp">
<div ng-controller="myCont">
{{Prop1}}
<input type="text" ng-model="Prop1" />
<mydir oneway={{Prop1}}></mydir>
</div>
</body>
</html>
標記
<b>HII</b>
{{oneway}}
<input type="text" ng-model="oneway" />
感謝這麼多提前..
感謝這麼多的小提琴。但我看到了多方向的數據流。我已經更新了小提琴演示它..你能檢查嗎?我只需要從Controller到Directive的單向流程。 – Ananth
然後只需使用'@'。我更新了小提琴https://jsfiddle.net/Tsalikidis/eg93q1rc/3/。只是不要使用單向名稱作爲綁定變量。我在小提琴中使用'x'。 – Masterakos
非常感謝......「只是不要使用單向名稱作爲綁定變量。」 ......問題的解決方案是「單向」還是保留字?你可以看到,即使在你的小提琴中,如果你用單向替換x,它也不會起作用 – Ananth