2017-03-07 90 views
0

我正在尝试创建一个可重用的html元素/ angular指令,这个指令将在ng-repeat内部使用,所以我想将它传递给它在DOM中显示的值。AngularJS将对象传入隔离范围

值得注意的是,我不在乎绑定的值。它们可以是一次性绑定,只需在第一次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> 

我从来没有创建迪在之前和我试图遵循的所有指南都没有解释范围,并且绑定发生在指令内部。

回答

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>

+0

谢谢这使得有很大的意义了。感谢您的浏览器演示。 –

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? 
    } 
}; 
});