Rem*_*ing 5 javascript angularjs angularjs-directive angularjs-scope
我有以下指令:
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 || '.*';
}
};
});
Run Code Online (Sandbox Code Playgroud)
使用以下模板:
<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>
Run Code Online (Sandbox Code Playgroud)
它由以下形式使用:
<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>
Run Code Online (Sandbox Code Playgroud)
哪个有这个控制器:
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;
});
};
}).
Run Code Online (Sandbox Code Playgroud)
表单渲染正常,但是当我单击Save按钮时,用户值永远不会更新.
如何在控制器范围内的myInput指令中使用更新的值?
这是基本问题.你ng-model是一个原始的,只是在一个方向上绑定...如果父对象被改变它将更新,但由于它是原始的,它不携带对父对象的引用...只是值.因此,更新原语不会更新其原始值来自的父对象
角度基本规则... 在ng-model中总是有一个点
这是一个将主user对象传递给指令范围的解决方案,以及用于每个输入的该对象的属性
<my-input id="firstName" model="user" field="firstName" label="First name"></my-input>
Run Code Online (Sandbox Code Playgroud)
现在需要将对象从控制器传递到指令范围:
app.directive('myInput', function() {
return {
scope: {
/* other props*/
field: '@',
model:'='/* now have reference to parent object in scope*/
},
......
};
});
Run Code Online (Sandbox Code Playgroud)
然后在输入的标记中将使用[]符号来获取我们的点:
<input ng-model="model[field]".../>
Run Code Online (Sandbox Code Playgroud)
为了使用角度验证你可能将不得不require在ngModel控制器的指令或使用嵌套表格