AngularJs 属性指令 2 路绑定

AngularJs Attribute Directive 2 Way Binding

本文关键字:绑定 指令 属性 AngularJs      更新时间:2023-09-26

我有一个这样的角度应用程序

普伦克

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 路数据绑定,我想要这样的东西,但数据被传递到指令属性,就像我在这里一样。

您可以使用隔离范围更简洁地执行此操作。

这是一个更新的 plunker。

您可以将指令的值与 value: '=valueDisplay' 双向绑定

=告诉 angular 你想要双向绑定:

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: { value: '=valueDisplay' },
      link: function (scope, element, attrs) {
      }
    };
  });