AngularJS将对象传递到隔离范围

时间:2017-03-07 19:00:56

标签: angularjs

我正在尝试创建一个可重用的html元素/ angular指令,它将在ng-repeat中使用,所以我想传递它将在DOM中显示的值。

值得注意的是,我不关心绑定的值。它们可以是一次性绑定,只需在ng-repeat创建它们时显示它们的值。

例如,这是我的指令:

 app.directive('newsListing', function () {
    return {
        restrict: 'AE',
        replace: 'true',
        templateUrl: '../Pages/Views/Templates/newsListing.html',
        scope: {},
        link: function (scope, elem, attrs) {
            //Fairly sure this is where the binding needs to happen?
        }
    };
});

我的HTML模板:

<div>
<span class="glyphicon glyphicon-list-alt logo-green"></span>
<label>{{DateValue}}</label>
<label>{{Category}}</label>
<label class="noBorder">{{Content}}</label>

我想要的最终产品是什么:

<news-Listing Date="{{someValue}}" Category="{{someValue}}" Content="{{someValue}}"></news-Listing>

我之前从未创建过指令,我试图遵循的所有指南都没有解释范围,以及绑定在指令内发生的方式。

2 个答案:

答案 0 :(得分:0)

试试这个

var app = angular.module('anApp', []);
app.controller('aCtrl', function($scope) {


$scope.data = [{date:"2000-12-12",category:"sport",content:"this is a test"}]
});
app.directive('newsListing', function () {
    return {
        restrict: 'AE',
        replace: 'true',
        template: '<div><label>{{date}}</label><p>{{category}}</p><p>{{content}}</p></div>',
        scope: {
          date:'@',
          category:'@',
          content:'@'
        },
        link: function (scope, elem, attrs) {
            
        }
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="anApp" ng-controller="aCtrl">
   <div ng-repeat="d in data">
   <news-listing date="{{d.date}}" category="{{d.category}}" content="{{d.content}}" ></news-listing>
   </div>
</div>

答案 1 :(得分:0)

以下是您想要的工作示例:https://jsfiddle.net/jonva/kuk3pbbz/

.directive('newsListing', function() {
return {
  restrict: 'AE',
  replace: 'true',
  template: '<div> < span class = "glyphicon glyphicon-list-alt logo-green" > < /span> < label > {{dateValue}} < /label> < label > {{category}} < /label> < label class = "noBorder" > {{content}} < /label>',
  scope: {
            dateValue: '@',
            content: '@',
            category: '@',

  },
  link: function(scope, elem, attrs) {
    //Fairly sure this is where the binding needs to happen?
  }
};
});