AngularJS ng-model不是双向绑定,作为指令的一部分

时间:2014-07-02 01:05:47

标签: javascript angularjs angularjs-directive angularjs-scope

我试图为货币输入制作一个简单的Angular指令。它应该在模型中表现为float,但它需要向用户显示a。它还需要强制显示2位小数。

我为它制作了以下代码:

//  Currency Input (Element Directive)
//  Simple text box that enforces 2 decimal place numeric input
//  Usage:
//      <currency
//          ng-model: string, angular model binding, optional
//      ></currency>
directives.directive('currency', function() {
    return {
        require: 'ngModel',
        restrict: 'E',
        replace: true,
        transclude: true,
        template: '<span class="currency"><input type="text" ng-model="text" ng-transclude /></span>',
        scope: {
            ngModel: '=amount'
        },
        link: function($scope) {
            return function($scope, elem, attrs, ctrl) {
                $scope.$watch("text", function(newVal) {
                    $scope.amount = parseFloat(newVal);
                    console.log();
                    console.log("text changed, recalculating amount");
                    console.log("Successfully converted", newVal, "into", $scope.amount);
                });
                $scope.$watch("amount", function(newVal) {
                    $scope.text = newVal.toFixed(2);
                    console.log();
                    console.log("amount changed, recalculating text");
                    console.log("Successfully converted", newVal, "into", $scope.text);
                });
            }
        },

        controller: function ($scope) {
            $scope.text = "test";
            $scope.amount = 0;

            grabScope = function() { //Debug function to allow global access to this scope
                return $scope;
            }
        }
    };
});

使用此指令创建一个包含单词&#34; test&#34;的文本框,但在该文本框中输入无法更新$ scope.text,因此无法启动监视并更新模型。

我在这里唠叨了一会儿,但我可能做了一些非常愚蠢的事情。有什么想法吗?

谢谢,

YM

1 个答案:

答案 0 :(得分:1)

我认为您的链接属性未正确实现。

应该是:

    link: function($scope, elem, attrs, ctrl) {
            $scope.$watch("text", function(newVal) {
                $scope.amount = parseFloat(newVal);
                console.log();
                console.log("text changed, recalculating amount");
                console.log("Successfully converted", newVal, "into", $scope.amount);
            });
            $scope.$watch("amount", function(newVal) {
                $scope.text = newVal.toFixed(2);
                console.log();
                console.log("amount changed, recalculating text");
                console.log("Successfully converted", newVal, "into", $scope.store.text);
            });
        }
    },