您好我对如何使用来自同一对象的不同数据绑定同一指令感到困惑
(function () {
'use strict';
angular.module('app', [])
.controller('appController', appController)
.directive('userForm', userForm);
/**@Injectable*/
function appController($http) {
let vm = this;
vm.user = {
userName: 'Test User',
email: 'test@gmail.com',
number: '1456',
address: 'zyz',
state: 'abcd',
city: 'xyz'
};
}
function userForm() {
return {
restrict: 'E',
scope: {
data:'='
},
templateUrl: 'public/app/form.directive.html',
controller: 'appController',
link: function (scope, attr, element) {
}
}
}
})();

<legend>{{headerLabel}}</legend>
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">{{label1.label1}}</label>
<div class="col-sm-9">
<input type="text" ng-model="data.userName" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">{{label2}}</label>
<div class="col-sm-9">
<input type="text" class="form-control" ng-model="email">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">{{label3}}</label>
<div class="col-sm-9">
<input type="text" class="form-control" ng-model="number">
</div>
</div>
<!--Main Index -->
<user-form data="vm.user"></user-form>
<user-form data="vm.user"></user-form>
&#13;
这里我使用了相同的指令两次,我想用第一个指令绑定个人信息,如用户名,电子邮件和第二个指令应该绑定地址信息。是否可以这样做?
答案 0 :(得分:0)
我想知道为什么你会这样做,使用指令用于两个不同的目的。我建议为它创建2个不同的指令。如果您仍然需要它,您可以在指令功能中使用逻辑内部链接来执行不同的逻辑。它不是很优雅,但你所要求的不是(imho)
(function () {
'use strict';
angular.module('app', [])
.controller('appController', appController)
.directive('userForm', userForm);
/**@Injectable*/
function appController($http) {
let vm = this;
vm.user = {
userName: 'Test User',
email: 'test@gmail.com',
number: '1456',
address: 'zyz',
state: 'abcd',
city: 'xyz'
};
}
function userForm() {
return {
restrict: 'E',
scope: {
data:'=',
type:'@'
},
templateUrl: 'public/app/form.directive.html',
controller: 'appController',
link: function (scope, attr, element) {
switch(scope.type){
case 'name_info':
//logic for name based info
break;
case 'address_info':
//logic for address based info
break;
default:
}
}
}
}
})();
<legend>{{headerLabel}}</legend>
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">{{label1.label1}}</label>
<div class="col-sm-9">
<input type="text" ng-model="data.userName" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">{{label2}}</label>
<div class="col-sm-9">
<input type="text" class="form-control" ng-model="email">
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label" for="textinput">{{label3}}</label>
<div class="col-sm-9">
<input type="text" class="form-control" ng-model="number">
</div>
</div>
<user-form data="vm.user" type="name_info"></user-form>
<user-form data="vm.user" type="address_info"></user-form>