[英]To pass an interpolated expression into an Angular Directive
我看過幾次這個問題。 但是無法以正確的方式實施那些答案中提到的解決方案。 我是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也只會被觸發一次。 更改{{Prop1}}不會觸發觀察功能。
使用watch \\ 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" />
非常感謝預先。
假設您的指令只應該看到它的初始值,就是這樣,並且一旦ng-model更新了相同的作用域參數就永遠不會更新,我建議一次綁定 (向下滾動以閱讀更多內容)
以
::
開頭的表達式被視為一次性表達式。 一次性表達式一旦穩定就會停止重新計算,如果表達式結果為非不確定值,則在第一次摘要后會發生。
請注意,唯一真正的區別是指令的模板,您現在在表達式中使用::
前綴來告訴angular綁定值,而不為此特定范圍的變量創建任何觀察程序。
演示: https : //jsfiddle.net/eg93q1rc/2/
使用Javascript:
angular
.module('testApp', [])
.controller('testCtrl', ['$scope', function($scope) {
$scope.Prop1 = 'TestProp1Text';
}])
.directive('myDir', function($parse) {
return {
scope: {
oneway: '='
},
template: '<span>{{::oneway}}</span>',
link: function(scope, element, attrs) {
}
};
});
HTML
<div ng-app="testApp" ng-controller="testCtrl">
<my-dir oneway="Prop1"></my-dir>
<input ng-model="Prop1">
</div>
這是您需要的小提琴。 https://jsfiddle.net/Tsalikidis/eg93q1rc/
<mydir oneway="foo"></mydir>
只需使用'='來指示范圍
...
scope: {
oneway: '='
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.