问题描述
我试图创建一个指令,该指令允许我将范围变量设置为作为数据属性传递的变量名称。
我目前有以下内容:
<input create-user-dropdown ng-model="userValue" data-my-var="myVar" />
app.directive('createUserDropdown', function(){
return {
restrict: 'A',
scope: {
myVarNameHere: "="
}
link: function(scope, elem, attr){
scope.$watch(attrs.ngModel, function (value) {
$scope.myVarNameHere = value;
});
}
};
});
如何使用通过data-my-var
传递的变量名称作为范围变量,而不是我的指令中当前名为myVarNameHere
?
1楼
尝试这样:
<input create-user-dropdown ng-model="userValue" data-my-var="myVar" />
app.directive('createUserDropdown', function(){
return {
restrict: 'A',
scope: {
myVarNameHere: "=myVar"
},
link: function(scope, elem, attr){
scope.$watch(attrs.ngModel, function (value) {
scope.myVarNameHere = value;
});
}
};
});
2楼
正如我们在注释中发现的那样,您可以使用模板创建指令,例如
.directive('myDir', function($http) {
return {
scope:{
val: '=',//variable from parent scope for handling input value, if result of input not used outside directive can be removed
template: '=' // template url for repeated div
},
template: '<input ng-model="val" ng-change="search()" />'+
'<div ng-repeat="item in founded" ng-include="template"></div>',
link: function link(scope, iElement, iAttrs, controller, transcludeFn) {
scope.search = function(){// create change handler
//use value `data-service` attribute as service name
$http.get(iAttrs.service).success(function(data){
scope.founded = data;
});
}
}
}
}
工作