1

我想为我的表单字段编写验证器。

就我而言,我有一个带有隐藏编辑表单和显示用户名列表的页面。单击列表中的一个用户名时,会在下方显示一个编辑字段,其中包含一个检查唯一指令。

我想在打开编辑表单后立即将参数值解析为指令。但是当然它们不会在指令中更新,因为页面已经编译并且值仅在页面加载期间解析为指令。因此,即使我想将用户名解析为属性值,我的 attr.checkUnique 值也是空的。

这是我的小提琴。 http://jsfiddle.net/charms/r3ajt/28/

有人知道在执行“openEdit”方法时是否可以以某种方式刷新指令以接管新参数?

或者有没有其他聪明的方法来克服这个问题?不知何故,我被困在这里。

HTML

<div ng-app="myApp" ng-controller="HandleCtrl">
<div ng-repeat="u in users">
    {{u.username}}<button ng-click="openEdit({{u.id}})">Edit</button><br/>
</div>
<form ng-show="showNew" novalidate>
    <input type="text" name="username"/>
</form>
<form ng-show="showEdit" novalidate>
    <input type="text" name="username" ng-model="user.username" check-unique="{{user.username}}"/>
</form>
</div>

AngularJS

angular.module('myApp', [])
.controller('HandleCtrl', ['$scope',function($scope) {
$scope.showNew = false;
$scope.showEdit = false;

$scope.user = {};
$scope.users = [];

$scope.users[0] = {username:'matt', id:1};
$scope.users[1] = {username:'bob', id:2};
$scope.users[2] = {username:'tom', id:3};

$scope.openEdit = function(id) {
    $scope.showEdit = true;
    $scope.user = $scope.users[id-1];
};
}])
.directive('checkUnique', [function() {
return {
    require: 'ngModel',
    restrict: 'A',
    scope: false,
    link: function(scope, elem, attr, ctrl) {
        console.log("I want username but value is empty: " + attr.checkUnique);
    }
};
}]);
4

2 回答 2

1

如果我了解您要正确实现的目标...

您需要watch在指令中更改模型。尝试这个:

.directive('checkUnique', [function() {
return {
    require: 'ngModel',
    restrict: 'A',
    scope: false,
    link: function(scope, elem, attr, ctrl) {
        scope.$watch('user.username', function(newValue, oldValue) {
            if (newValue) {
                console.log('Username selected is ' + newValue);
            }
        });
    }
};

由于您的指令正在共享它的父范围(如您的指令定义中所指定),因此您可以直接访问“user.username”。

于 2013-09-05T20:12:51.433 回答
0

您可以使用 croller 选项以及模型更新时的内容来访问您的模型。这是您可以做什么以及如何访问您的模型的完整示例。

.directive('checkUnique', [function() {
    return {
        require: 'ngModel',
        restrict: 'A',
        scope: false,
        link: function(scope, elem, attr, ctrl) {
            scope.$watch(attr.ngModel, function(nv) { // Don't watch ctrl.$viewValue cause it won't watch.
                console.log("I want username but value is empty: " + nv); // When 
                if (nv.indexOf('is magic') === -1) { // Don't want infinite loop.
                    ctrl.$setViewValue(nv +  ' is magic'); // Set a new value to model.
                }

                console.log('My current value is ' + ctrl.$viewValue); // Accessing model scope.
            });
        }
    };
}]);

这是您的jsFiddle更新。

于 2013-09-05T21:51:07.367 回答