javascript - 如何在 Angular 指令中使用动态作用域名称?

标签 javascript angularjs

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

我目前有以下内容:

<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/

相关文章:

javascript - 带有图像的水平下拉选择

javascript - 如何直接在另一个网站中显示一个完整的网站..?

angularjs - Angular 2 变化检测是如何工作的?

ruby-on-rails - 什么是本地主机 :8000 as used in Codecademy (for AngularJS and Ruby on Rails tutorials)?

javascript - 尝试使用 ng-repeat 时出现黑屏?

html - 如果未在其上方单击,则 Bootstrap 弹出窗口隐藏

javascript - 使用预先保存的信息在网站上填写表格?

javascript - 在canplaythrough 上淡出 HTML5 视频海报图像

javascript - 在 Javascript 中创建变量的实例并在匿名函数中访问变量

javascript - 如何制作 javascript 下载文件?