如何通过NG-BIND-HTML通过自定义指令传递和更新数据



我想添加一个常见的自定义指令,当实例化时,将通过字符串输入查看并使用适当的电话html返回字符串。目前,逻辑在消息指令中,在html中,我有:

<div ng-repeat="message in messages >
            <p ng-bind-html=message.title</p> 
        </div>

和指令我有:

.directive('message', function () {
        return {
            scope: {
                messages: "=messages",
            },
            restrict: 'E',
            controller: 'MessageSummary',
            controllerAs: 'messageSummary'
        };
    })
.controller('MessageSummary', ['$scope', function ($scope) {
  angular.forEach($scope.messages, function (message, index) {
     $scope.messages[index].title = wrapStringWithPhoneNumberHTMLTag($scope.messages[index].title);
  });

我需要将此逻辑提取到其自己的指令中,以便可以在任何地方重复使用。目前我添加了:

<div ng-repeat="message in messages >
            <p ng-bind-html=message.title ng-phone-caller=message.title</p> 
        </div>

.directive('ngPhoneCaller',function() {
       return {
           scope: {
               inputString: '='
           },
           link: function (scope) {
               scope.inputString = wrapStringWithPhoneNumberHTMLTag(scope.inputString);
           }
       }

但它的范围。传递到函数中的输出条件是不确定的。另外,我对如何将其与ng-bind-html-->集成在一起有些遗失,我需要它来验证返回的HTML字符串,然后将其传递到自定义的公共指令中。另外,这是最好的方法吗?似乎有人使用我的属性自定义指令,他们需要实现ng-bind-html,是否有一种方法可以在自定义指令中安全地集成html?

通过将数据传递到模板布局

的基本示例

var app = angular.module('myApp', []);
app.controller('MyController1', function ($scope) {
  $scope.data = [
    {
      'title': 'one'
    },
    {
      'title': 'two'
    },
    {
      'title': 'three'
    }
  ];
});
app.controller('MyController2', function ($scope) {
  $scope.data = [
    {
      'title': 'satu'
    },
    {
      'title': 'dua'
    },
    {
      'title': 'tiga'
    }
  ];
});
app.directive('myDirective', function () {
  'use strict';
  return {
    restrict: 'E',
    scope: {
      data: '=data'
    },
    template: [
      '<div ng-repeat="record in data">',
        '{{ record.title }}',
      '</div>'
    ].join('')
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyController1">
    <my-directive data="data">
  </div>
  <br >
  <div ng-controller="MyController2">
    <my-directive data="data">
  </div>
</div>

最新更新