如何$在angularjs中观察多个变量?

时间:2013-03-12 07:57:35

标签: angularjs

这是一个angularjs指令,用于显示多个表单验证错误 指令代码 -

app.directive('validationErrors', function($compile) {
    return({
        link : function($scope, el, attr) {

            $scope.fld = attr.id;
            $scope.individualValidationErrors = [];
            var model = ((attr.ngModel).split('.'))[0];

            $scope.validationErrors = {};
            $scope.validationErrors[model] = {};
            $scope.validationErrors[model][$scope.fld] = "";

            var html = $compile(
                '<div id="error-{{fld}}" style="color:red;">'+
                    '<ul>' +
                        '<li ng-repeat="error in individualValidationErrors[fld]">'+
                            '{{error}}' +
                        '</li>' +
                    '</ul>' +
                '</div>'
            )($scope);
            $('input[id="'+$scope.fld+'"]').after(html);

            $scope.$watch('validationErrors',
                function(newV) {
                    $scope.fld = attr.id;
                    $scope.individualValidationErrors = [];

                    console.log(newV);
                    console.log($scope.validationErrors);

                    if ($scope.fld != undefined) {
                        $scope.individualValidationErrors[$scope.fld] = $scope.validationErrors[model][$scope.fld];
                        //console.log($scope.individualValidationErrors);
                    }
                },
                true
            );
        }
    });
});

Html代码 -

<form ng-submit="registration()">
    <input validation-errors="validationErrors" maxlength="50" type="text" id="first_name" ng-model="User.first_name">
    <input validation-errors="validationErrors" maxlength="50" type="text" id="last_name" ng-model="User.last_name">
    <input validation-errors="validationErrors" maxlength="50" type="text" id="email" ng-model="User.email">
    <input validation-errors="validationErrors" type="password" id="password"  ng-model="User.password">
    <input class="btn btn-info" type="submit" id="registration-sbmit" value="Submit">
</form>

表单的最后一个字段的错误会覆盖表单中的所有字段,因此它不会显示字段的单个错误。 $ scope.validationErrors变量在控制器中设置,我希望$ watch in directive。

2 个答案:

答案 0 :(得分:1)

我认为你的主要问题是你在链接函数中覆盖了$ scope.validationErrors。将为页面上的每个指令运行链接功能。它们也共享相同的$ scope对象。因此,您需要有条件地创建$ scope.validationErrors并有条件地向其添加顶级键:

if(!$scope.validationErrors)
    $scope.validationErrors = {};
if(!$scope.validationErrors[model])
    $scope.validationErrors[model] = {};
$scope.validationErrors[model][$scope.fld] = "";

至少应该清除你在$ scope.validationErrors中获取最后一项的问题。

答案 1 :(得分:0)

你可以这样做:

$scope.$watch('[myproperty1,myproperty2,myproperty3]',function(nv,ov){
//do some stuff
});