我几次问过这个问题 . 但是无法以正确的方式在这些答案中实现解决方案 . 我是Angular的新手,并尝试使用Observe或watch来将插值表达式传递给自定义指令以获得单向绑定 .
我不确定使用$ 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
-
即使我在指令中有一个表达式,$ observe也只被触发一次 . 更改{}不会触发观察功能 .
-
我尝试使用$ watch而不是$ observe . 但仍面临同样的问题
使用observe \ watch获取控制器和指令之间的单向绑定的正确方法是什么?
遵循完整的代码
<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>
模板中的标记(HtmlPage1.html)
<b>HII</b>
{{oneway}}
<input type="text" ng-model="oneway" />
非常感谢提前..
2 回答
这是你需要的小提琴 . https://jsfiddle.net/Tsalikidis/eg93q1rc/
并且只需使用'='来指示范围
假设你的指令只应该看到它's initial value and that'并且一旦ng-model更新相同的作用域参数就永远不会更新,我建议One Time Binding(向下滚动以阅读更多内容)
请注意,唯一真正的区别在于您的指令的模板,您现在使用表达式中的
::
前缀来告诉angular绑定值,而不是为此特定范围变量创建任何观察者 .演示:https://jsfiddle.net/eg93q1rc/2/
使用Javascript:
HTML