【问题标题】:Dynamic add attributes on component in Angular pre compileAngular预编译中组件的动态添加属性
【发布时间】:2017-07-04 09:15:06
【问题描述】:

我有多次使用的组件,58 次是 exakt。它们之间唯一不同的是添加验证的独特属性。我想要做的是在编译之前向我的模板添加一组属性。这在使用 Angular 组件时是否可以实现?

component.js

(function () {
    'use strict';

    angular
        .module('upaApp')
        .component('component', {
            bindings: {
                inputAttributes: '@',
            },
            controller: controller,
            restrict: 'E',
            templateUrl: 'app/component/component.html'
        });

    function controller() {
        var $ctrl = this;
    }
})();

component.html

<input {{ $ctrl.inputAttributes }}
       class="form-control"
       type="text" />

当我使用组件&lt;component input-attributes="directive1, directive2"&gt;&lt;/component&gt; 时,它不会渲染出我的字符串,即使它渲染出来,我也不确定它是否会工作。那么有没有办法在AngularJS中动态设置属性呢?

【问题讨论】:

    标签: angularjs angular-components


    【解决方案1】:

    我的问题实际上有一个非常简单的解决方案。您可以使用 ng-model 将值发送到组件。当我将指令放在组件上时,它会相应地进行验证,因为它可以访问来自 ng-model 的值。

    【讨论】:

      【解决方案2】:

      这是角度 1 还是 2? 我假设前者。

      我不知道将字符串作为属性放置的方法。作为一种解决方法,您可以做的是有条件地插入带有 ng-attr- 属性的属性。如果变量未定义,这将插入属性。 也许是这样的:

      $scope.ctrl.inputAttributes = {
          directive1:undefined, //this one wont show 
          directive2:"this one will show"// as directive2="this one will show"
      }
      

      然后在您的标记中:

      <input ng-attr-directive1="ctrl.inputAttributes.directive1"
             ng-attr-directive2="ctrl.inputAttributes.directive2"
             class="form-control"
             type="text" />
      

      https://www.thinkingmedia.ca/2015/03/conditionally-add-a-html-element-attribute-value-in-angularjs/

      编辑:它可能不干净,但您可以创建一个编译 html 的指令。

      app.directive('dynamicAttributes', function ($compile) {
      return {
          restrict: 'E',
          scope: {
              attributes: '@'
          },
          link: function (scope, elem, attrs) {
              var h = '<input '+scope.attributes + ' class="form-control" type="text" />';
              elem.replaceWith($compile(h)(scope));
          }
      }
      });
      

      然后在你的 DOM 中

      <dynamic-attributes attributes="1 2 3"></dynamic-attributes>
      

      小提琴:http://jsfiddle.net/brhardwick/nx16zdrL/1/

      【讨论】:

      • 这是 Angular 1,他们指出的方式是我们今天解决的方式。我们有 85 条指令,所以这不是一个好的解决方案。
      • 检查我的编辑。如果指令很复杂,您可能需要进行调整。但这应该会让你继续前进
      猜你喜欢
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2021-08-20
      • 2022-08-17
      • 2020-03-22
      • 2017-07-17
      • 2021-12-17
      • 1970-01-01
      相关资源
      最近更新 更多