如何在Angular中动态地将模板附加到页面

时间:2015-08-13 23:37:13

标签: javascript angularjs angularjs-directive angularjs-ng-repeat

情况如下:

我有一个输入栏,用户可以在其中搜索公司名称或添加人员姓名(以及选择任一选项的按钮)。点击进入后,我想附加一个模板的唯一实例(添加用户输入的信息)。我创建了2个模板,具体取决于用户是在搜索公司还是个人。

我考虑过的一种方法是使用数据创建一个对象并添加ng-repeat,但是我似乎无法加载数据,即使这样也不知道我如何在我的收藏中存储对模板的引用。

我遇到的另一个想法是添加自定义指令。但即使如此,我还没有看到一个例子,其中某人不断追加具有不同数据的模板的新实例。

以下是目前的代码:

payments.js:

angular.module('payment-App.payments',['ngAutocomplete'])

  .controller('paymentController', function($scope, $templateRequest/*, $cookieStore*/) {

    $scope.businessID;
    $scope.address;
    $scope.isBusiness = false;
    $scope.payees = [];

    $scope.newPayee = function () {
      this.businessID = $scope.businessID;
      this.address = $scope.address;
    }

    $scope.submit = function () {
      var text = document.getElementById("businessID").value.split(",");
      $scope.businessID = text[0];
      $scope.address = text.slice(1).join("");
      $scope.newPayee();
    }

    $scope.addPayee = function () {
      $scope.submit();
      $scope.payees.push(new $scope.newPayee());
      console.log($scope.payees);
    }

    $scope.selectBusiness = function () {
      //turns on autocomplete;
      $scope.isBusiness = true;
    }

    $scope.selectPerson = function () {
      //turns off autocomplete
      $scope.isBusiness = false;
    }

    $scope.fillAddress = function () {
      // body...
    }

})

  .directive("topbar", function(){
  return {
    restrict: "A",
    templateUrl: 'templates/businessTemplate.html',
    replace: true,
    transclude: false,
    scope: {
      businessID: '=topbar'
    }
  }
})

payments.html

<h1>Payments</h1>

<section ng-controller="paymentController">


<div>

  <div class="ui center aligned grid">

    <div class="ui buttons">
      <button class="ui button" ng-click="selectBusiness()">Business</button>
      <button class="ui button arrow" ng-click="selectPerson()">Person</button>
    </div>

    <div class="ui input" ng-keypress="submit()">
      <input id="businessID" type="text" ng-autocomplete ng-model="autocomplete">
    </div>


    <div class="submit">
      <button class="ui button" id="submit" ng-click="addPayee()">
        <i class="arrow right icon"></i>
      </button>
    </div>

  </div>

  <div class="search"></div>


  <div class="payments" ng-controller="paymentController">
    <li ng-repeat="newPayee in payees">{{payees}}</li>
  </div>

  <!-- <topbar></topbar> -->

</div>

(示例模板) businessTemplate.html:

 <div class="Business">
   <div class="BusinessName" id="name">{{businessID}}</div>
   <div class="Address" id="address">{{address}}</div>
   <button class="ui icon button" id="hoverbox">
     <i class="dollar icon"></i>
   </button>
 </div>

1 个答案:

答案 0 :(得分:0)

我最终在这里使用了ng-repeat的解决方法。尽管如此仍然对原始问题感到好奇。