我正在尝试创建一个指令。我一直在遵循 john papa 自以为是的风格指南并将控制器用作 vm。不幸的是,当我尝试制定指令时,我不确定如何在不使用 $scope 而不是 vm 的情况下做到这一点。
(最后一个标签应该是 angularjs-styleguide 但我找不到,而且我没有足够的积分来制作新标签)
这是plunkr。 https://plnkr.co/edit/DYTJURgaLd0QadcCSPFW?p=preview
<script src="https://code.angularjs.org/1.5.5/angular.js"></script>
<script src="./script.js"></script>
<script src="./directive.js"></script>
<div ng-app="myApp">
<div ng-controller="myCtrl as vm">
<div unordered-list="products" list-property="price | currency"></div>
<!-- this does not work
<div unordered-list="vm.products" list-property="price | currency"></div>
-->
</div>
</div>
控制器
(function() {
'use strict';
angular
.module('myApp', [])
.controller('myCtrl', myCtrl);
myCtrl.$inject = ['$scope'];
function myCtrl($scope){
/* jshint validthis: true */
var vm=this;
$scope.products = [
{ name: "Apples", category: "Fruit", price: 1.20, expiry: 10 },
{ name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 },
{ name: "Pears", category: "Fruit", price: 2.02, expiry: 6 },
];
vm.products = [
{ name: "Apples", category: "Fruit", price: 1.20, expiry: 10 },
{ name: "Bananas", category: "Fruit", price: 2.42, expiry: 7 },
{ name: "Pears", category: "Fruit", price: 2.02, expiry: 6 },
];
}
})();
指示
angular.module("myApp")
.directive("unorderedList", function () {
return {
link: function (scope, element, attrs) {
scope.data = scope[attrs["unorderedList"]];
},
restrict: "A",
template: "<ul><li ng-repeat='item in data'>"
+ "{{item.price | currency}}</li></ul>",
replace: true
};
});