我正在尝试创建一个指令,允许我将范围变量设置为作为数据属性传递的变量名称。
我目前有以下内容:
<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
的变量名称?
最佳答案
正如我们在评论中发现的,您可以使用类似的模板创建指令
.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;
});
}
}
}
}
正在工作 plunkr
关于javascript - 如何在 Angular 指令中使用动态作用域名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31473751/