0

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

普朗克

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

4

1 回答 1

3

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

这是一个更新的plunker

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

=告诉你想要双向绑定的角度:

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) {

      }
    };
  });
于 2013-10-28T09:54:49.453 回答