4

I'm trying to create a set of DSLs using Angular directives to have dynamic templating for some simple form elements based on data-type. I'm looking for some help in getting the binding to work as well as more theoretical help as to whether or not this is the 'right approach' in terms of best-practices etc...

It might be easier if I show you what I'm trying to achieve as I'm still very green when it comes to Angular.

Example usage code:

<h2>{{data.title}}</h2>
<shorttext label="Title" id="title" />
<longtext label="Body" id="body" />
<usagerights label="Usage Rights Restriction" id="usageRights" />

Outputted as:

<div>
  <label for="{{id}}">{{label}}</label>
  <input type="text" ng-model="data.{{id}}" />
</div>
<div>
  <label for="{{id}}">{{label}}</label>
  <textarea ng-model="data.{{id}}"></textarea>
</div>
<div>
  <label for="{{id}}">{{label}}</label>
  <select id="{{id}}" ng-model="data.{{id}}">
    <option value="">None</option>
    <option value="limited">Limited</option>
    <option value="unlimited">Unlimited</option>
  </select>
</div>

I've had a play and come up with something similar to this:

var myApp = angular.module("myApp", []).directive('shorttext', function(){
  return {
      restrict: "E",
      replace: true,
      template: "<div><label for='{{id}}'>{{label}}</label><input id='{{id}}' ng-model='data.{{id}}' type='text' class='span6' /></div>",
      scope: {
          id: "@id",
          label: "@label"
      }
    };
});

Here's a dummy controller to try to get the scope to work:

myApp.controller('FormCtrl', ['$scope', function($scope) {
  $scope.data = {title:'test', body:'some text', usageRights:'limited'};
}]);

Part of the reason for wanting to use DSLs in such a way is for legacy compatibility and also for re-usability of the presentation rules for custom fields such as usage-rights.

I'm looking for advice on if this is even a reasonable expectation of the framework, how I'd get the binding to work with ng-model (I've had a look at things like 'compile' that are available on directives, but am a bit out of my depth of what it all really does).

TL;DR: I would like custom form tags that transform into different elements based on directive templates with two-way binding. Advice on implementation greatly appreciated.

Thanks, Gaz

4

1 回答 1

2

I'd take the silence thus far on your post as general approval. Nobody has much to add. All your general principles make sense to me, and you're doing a nice job of using declarative property names to make your components reusable.

For that reason, I won't be surprised if somebody comes along and tags this with 'not appropriate', as there isn't much of a concrete technical answer to your question. But, that's 'cause you seem to be doing it right. Cheers.

于 2013-11-05T00:25:00.493 回答