【问题标题】:How to use same html but different model values in angular js?如何在angular js中使用相同的html但不同的模型值?
【发布时间】:2017-04-15 00:16:05
【问题描述】:

我有一个场景,其中两个部分的html 相同但模型不同。例如看下面的代码

 <ul class="feeds">
    <li ng-if="scleanerData.contact_no">
      <div><i class="fa fa-phone color-grey" aria-hidden="true"></i></div>{{scleanerData.contact_no}}</li>
    <li ng-if="scleanerData.email">
      <div><i class="fa fa-envelope color-grey" aria-hidden="true"></i></div>{{scleanerData.email}}</li>
    <li ng-if="scleanerData.address">
      <div><i class="fa fa-globe color-grey" aria-hidden="true"></i></div>{{scleanerData.address}}</li>
  </ul>

我在第二部分需要同样的html,但这次绑定是这样的

<ul class="feeds">
        <li ng-if="profile.house">
          <div><i class="fa fa-phone color-grey" aria-hidden="true"></i></div>{{profile.house}}</li>
        <li ng-if="profile.email">
          <div><i class="fa fa-envelope color-grey" aria-hidden="true"></i></div>{{profile.email}}</li>
        <li ng-if="profile.home}">
          <div><i class="fa fa-globe color-grey" aria-hidden="true"></i></div>{{profile.home}}</li>
      </ul>

有什么方法可以让我编写一次 html,但数据绑定对它们都有效。

【问题讨论】:

    标签: angularjs data-binding angular-directive partials


    【解决方案1】:

    使用此 html 作为模板并具有隔离范围创建自定义指令。在需要的地方使用该指令,并将模型作为输入从不同位置传递给该指令。

    以下是简短的示例,可能会对您有所帮助。

    定义指令:

    app.directive('myDirective', function(){
      return {
        restrict: 'E',
        scope: {
          contactInfo: '='
        },
        templateUrl: 'my-template.html',
        link: function (scope,element,attrs,ctrl){
          // you can manipulate your data / DOM here, if required.
        }
      }
    })
    

    关联一个指令 HTML:

    <ul class="feeds">
      <li ng-if="contactInfo.contact_no">
        {{contactInfo.contact_no}}</li>
      <li ng-if="contactInfo.email">
        {{contactInfo.email}}</li>
      <li ng-if="contactInfo.address">
        {{contactInfo.address}}</li>
    </ul>
    

    在您的主 HTML 中使用该指令:

    <button ng-click="showInfo1 = true;showInfo2=false;">Show Info 1</button>
    <button ng-click="showInfo2 = true;showInfo1=fasle;">Show Info 2</button>
    <my-directive contact-info="contactInfo1" ng-show="showInfo1"></my-directive>
    <my-directive contact-info="contactInfo2" ng-show="showInfo2"></my-directive>
    

    请戳这里:https://plnkr.co/edit/EknrkUBBRl4rr7kma1Yw?p=preview

    【讨论】:

    • 用一个简短的例子更新了我的答案。请看一看。
    • $scope.contactInfo1 = {contact_no: "123456789",email: "test@test.test",address: "myaddress"}; $scope.contactInfo2 = {contact_no:“1234567891”,电子邮件:“test1@test1.test1”,地址:“myaddress1”};你为什么使用相同的字段,电子邮件联系号码和地址
    • 因为两个模型的对象类型相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-09
    • 1970-01-01
    • 2018-05-16
    • 2015-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多