我有一个像这样的角度应用程序
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="angular.js@*" 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>
好的,所以这可行,但我想知道是否没有更好的方法来执行我在此处设置的这种 2 方式绑定?
请记住,我想要独立作用域并且我知道我可以定义额外的属性并使用“=”在父作用域和独立作用域之间进行 2 路数据绑定我想要这样的东西,但是数据被传递到指令属性就像我在这里。