当前位置: 代码迷 >> JavaScript >> 如何在Angular指令中使用动态范围名称?
  详细解决方案

如何在Angular指令中使用动态范围名称?

热度:27   发布时间:2023-06-12 14:18:59.0

我试图创建一个指令,该指令允许我将范围变量设置为作为数据属性传递的变量名称。

我目前有以下内容:

<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

尝试这样:

<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;
            });
        }
    };
});

正如我们在注释中发现的那样,您可以使用模板创建指令,例如

.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;
        });
      }    
    }

  }
}

工作