0

我正在尝试创建一个指令。我一直在遵循 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
        };
    });
4

1 回答 1

1

如果您scope: { data: '=unorderedList' }在指令中指定,角度将自动将 的值拉vm.products入指令的范围,并且它将在data变量下可用。此外,不需要该link()功能。

angular.module("myApp")
    .directive("unorderedList", function () {
        return {
            scope: { data: '=unorderedList' },
            restrict: "A",
            template: "<ul><li ng-repeat='item in data'>"
            + "{{item.price | currency}}</li></ul>",
            replace: true
        };
    });
于 2018-01-28T01:16:20.710 回答