所以您似乎希望拥有任意数量的页面,它们看起来几乎相同,但每个标签、每个标题和帮助文本等都有不同的文本?
为了解决这个问题,我们只需要一个常规视图(模板)和在不同路径(范围)上保存不同数据的变量。
你需要angular-route。
有一个教程似乎与您想要做的非常接近。
https://docs.angularjs.org/tutorial/step_07
var formApp = angular.module('formApp', [
'ngRoute',
'formAppControllers'
]);
formApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/first', {
templateUrl: 'form.html',
controller: 'firstCtrl'
}).
when('/second', {
templateUrl: 'form.html',
controller: 'secondCtrl'
})
.otherwise({
redirectTo: '/first'
});
}]);
var formAppControllers = angular.module('formAppControllers', []);
formAppControllers.controller('firstCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.title = 'First Title';
$scope.firstLabel = 'First Label';
}]);
formAppControllers.controller('secondCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.title = 'Second Title';
$scope.firstLabel = 'Second Label';
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.9/angular.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.9/angular-route.min.js"></script>
<script type="text/ng-template" id="form.html">
<div class="view">
<h2>{{title}}</h2>
<label>{{firstLabel}}</label>
<input type="text" ng-model="firstInput">
</div>
</script>
<div ng-app="formApp">
<div ng-view></div>
</div>
不同的文本字符串在模板中用 {{}} 绑定到控制器中的 $scope。
每个路由都有一个单独的控制器,用于将数据填充到 $scope。 (您也可以使用 routeParams 来只拥有一个控制器)。
您可以像这样将模板内联,或者放在单独的文件中。
请注意,此示例不会在 stackoverflow 中运行,但应该可以帮助您进行操作。
原答案
也许像这样的动态 templateUrl 取决于类型?
.directive('cmsInput', function() {
return {
restrict: 'E',
require: '^ngModel',
templateUrl: function(elem, attr) {
return 'cmsinput-' + attr.type + '.html';
}
};
});
您也可以使用动态模板,在 scope.type 上使用 ng-switch。
directive.cmsinput.js
.directive('cmsInput', function() {
return {
restrict: 'E',
require: '^ngModel',
scope: {
default: '@default',
name: '@name',
size: '@size',
type: '@type'
},
templateUrl: directive.cmsinput.html
};
});
directive.cmsinput.html
<label>{{label}}</label>
<section ng-switch="type">
<div ng-switch-when="textarea">
<textarea ng-model="$parent.something" placeholder="{{placeholder}}">
</div>
<div ng-switch-default>
<input type="text" ng-model="$parent.something">
</div>
</section>
注意 $parent 的使用,因为 ng-switch 创建了一个子作用域,并且您可能希望字段值传播到指令的作用域。