我有一個角應用這樣AngularJs屬性指令2雙向綁定
的Javascript:
(function(angular, module){
module.controller("TestController", function($scope){
$scope.magicValue = 1;
});
module.directive("valueDisplay", function() {
return {
restrict: "A",
template: '<span>Iso Val: </span>{{ value }}<br/><span>Iso Change: </span><input data-ng-model="value" />',
replace: false,
scope: { },
link: function (scope, element, attrs) {
var pValKey = attrs.valueDisplay;
// Copy value from parent Scope.
scope.value = scope.$parent[pValKey];
scope.$parent.$watch(pValKey, function(newValue) {
if(angular.equals(newValue, scope.value)) {
// Values are the same take no action
return;
}
// Update Local Value
scope.value = newValue;
});
scope.$watch('value', function(newValue) {
if(angular.equals(newValue, scope.$parent[pValKey])) {
// Values are the same take no action
return;
}
// Update Parent Value
scope.$parent[pValKey] = newValue;
});
}
};
});
}(angular, angular.module("Test", [])));
HTML:
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]*" data-semver="1.2.0-rc2" src="http://code.angularjs.org/1.2.0-rc.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="Test">
<div ng-controller="TestController">
<ol>
<li>
<span>Parent Val: </span>{{ magicValue }}<br/>
<span>Parent Change:</span><input data-ng-model="magicValue" />
</li>
<li data-value-display="magicValue"></li>
</ol>
</div>
</body>
</html>
好了,所以這個工作,而且幾乎我想知道是否沒有更好的方式來完成這兩個綁定,我已經在這裏設置?
請記住,我想隔離範圍&,我知道我可以定義額外的屬性,並使用'='有雙向數據綁定之間的父母和孤立範圍我想這樣的事情,但數據獲取像我在這裏一樣傳遞給指令屬性。
什麼是使用範圍阻止你:{valueDisplay:「 = valueDisplay'}?您不必設置手錶,並且該值仍然屬於某個屬性。使用$ parent也很脆弱,因爲您永遠無法確定該值實際上是在父級中設置的。 – Narretz