我有一个简单的应用程序,从阵列中列出一个"汽车".当用户点击按钮时,显示来自阵列的下一辆车.
控制器:
var parking = angular.module("parking", []); // Registering the parkingCtrl to the parking module parking.controller("parkingCtrl", function ($scope) { // Binding the car’s array to the scope $scope.cars = [ {plate: '6MBV006'}, {plate: '5BBM299'}, {plate: '5AOJ230'} ]; $scope.idx = 0; $scope.next = function(){ $scope.idx = $scope.idx+1; if ($scope.idx>=$scope.cars.length) $scope.idx = 0; } });
"视图":
{{car.plate}}
如何以这种方式在单个页面上显示几个不同的汽车阵列,每个阵列都有自己的控件(在这种情况下,唯一的控件是"魔术"按钮)?
UPD:当然,我可以创建一个必需的ng-app nuber,每个都有自己的控制器副本("parkingCtrl1","parkingCtrl2"......"parkingCtrl10").但我想这不是最好的方式:)
好的,所以我会为此建立指令:
(function () { 'use strict'; /** * @ngdoc directive * @description * */ angular .module('yourModule') .directive('cars', cars); cars.$inject = ['']; function cars() { return { restrict: 'E', scope: { dataset: '=' }, controller: function ($scope) { $scope.next = function () { }; }, template: '\n' }; } }());\n \n \n \n{{car.plate}} \n\n
控制器:
(function() { 'use strict'; angular .module('yourModule') .controller('carsCtrl', carsCtrl); carsCtrl.$inject = ['$scope']; function carsCtrl($scope) { $scope.yourCarArray = [ {plate: '6MBV006'}, {plate: '5BBM299'}, {plate: '5AOJ230'} ]; $scope.yourCarArray2 = [ {plate: '6MBV006'}, {plate: '5BBM299'}, {plate: '5AOJ230'} ]; $scope.yourCarArray3 = [ {plate: '6MBV006'}, {plate: '5BBM299'}, {plate: '5AOJ230'} ]; $scope.yourCarArray4 = [ {plate: '6MBV006'}, {plate: '5BBM299'}, {plate: '5AOJ230'} ]; $scope.yourCarArray5 = [ {plate: '6MBV006'}, {plate: '5BBM299'}, {plate: '5AOJ230'} ]; } })();
在您的html文件中只需输入此指令:
因为它是一个指令,你可以多次重复使用它,例如: