gpt4 book ai didi

javascript - 在指令中观看 ng-model

转载 作者:数据小太阳 更新时间:2023-10-29 05:55:04 30 4
gpt4 key购买 nike

我有以下指令:

directive('myInput', function() {
return {
restrict: 'AE',
scope: {
id: '@',
label: '@',
type: '@',
value: '='
},
templateUrl: 'directives/dc-input.html',
link: function(scope, element, attrs) {
scope.disabled = attrs.hasOwnProperty('disabled');
scope.required = attrs.hasOwnProperty('required');
scope.pattern = attrs.pattern || '.*';
}
};
});

使用以下模板:

<div class="form-group">
<label for="input-{{id}}" class="col-sm-2 control-label">{{label}}</label>
<div class="col-sm-10" ng-switch on="type">
<textarea ng-switch-when="textarea" ng-model="value" class="form-control" id="input-{{id}}" ng-disabled="disabled" ng-required="required"></textarea>
<input ng-switch-default type="{{type}}" ng-model="value" class="form-control" id="input-{{id}}" ng-disabled="disabled" ng-required="required" pattern="{{pattern}}"/>
</div>
</div>

它被这种形式使用:

<form ng-controller="UserDetailsCtrl" role="form" class="form-horizontal">
<div ng-show="saved" class="alert alert-success">
The user has been updated.
</div>
<my-input label="First name" value="user.firstName" id="firstName"></my-input>
<my-input label="Last name" value="user.lastName" id="lastName"></my-input>
<my-input label="Email" value="user.email" id="email" type="email" disabled></my-input>
<my-input label="Password" value="user.password" id="password" type="password"></my-input>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button ng-click="update()" class="btn btn-default">Save</button>
</div>
</div>
</form>

哪个有这个 Controller :

controller('UserDetailsCtrl', function($scope, $stateParams, User) {
$scope.user = User.get({userId: $stateParams.id});
/**
* Update the current user in this scope.
*/
$scope.update = function() {
console.log($scope.user);
$scope.user.$update({userId: $scope.user.id}).then(function(results) {
$scope.saved = true;
});
};
}).

表单呈现良好,但当我单击 Save 按钮时,用户值永远不会更新。

如何在 Controller 范围内使用 myInput 指令中的更新值?

最佳答案

这是基本问题。你的 ng-model 是一个原始的并且只被绑定(bind)在一个方向上......如果父对象改变它会更新,但因为它是原始的它不携带对父对象的引用......只是值(value)。因此更新原语不会更新其原始值来自的父对象

Cardinal rule in angular...always have a dot in ng-model

这是一个解决方案,它将主要的 user 对象传递给指令范围,以及该对象的属性以用于每个输入

<my-input id="firstName" model="user" field="firstName" label="First name"></my-input>

现在需要将对象从 Controller 传递到指令范围:

app.directive('myInput', function() {
return {
scope: {
/* other props*/
field: '@',
model:'='/* now have reference to parent object in scope*/
},
......
};
});

然后在输入标记中将使用 [] 表示法以获得我们的:

<input  ng-model="model[field]".../>

DEMO

为了使用 Angular 验证,您可能必须在指令中要求 ngModel Controller 或使用嵌套形式

关于javascript - 在指令中观看 ng-model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20828046/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com