angularjs指令使用控制器作为vm而不是作用域

时间:2018-01-28 01:04:29

标签: javascript angularjs angularjs-directive angular2-styleguide

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

1 个答案:

答案 0 :(得分:1)

如果您在指令中指定scope: { data: '=unorderedList' },则angular会自动将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
        };
    });