0

I'm fairly new to angular and have set a project up using requirejs and angular but doing fairly simple stuff with UI.

My question is using angular, how do you go about creating a component/control that can be reused and added to at runtime. For example, in jquery I'd probably create a plugin and dynamically add dom elements before calling the plugin on the element.

i.e. $(el).append("").mycontrol({opts:1});

I've not really started with angular templates and repeats but thinking this is possibly the way to go, but how to you "bootstrap" new controls added dynamically.

The example I have in mind is that i'm using ui-select2 (AngularUI) and I would like to include the select2 component in some panels that are dynamically added to the dom.

The other solution of course would be to call the select2 function from the ng controller that added the host dom element.

any info welcomed

sambomartin
  • 6,663
  • 7
  • 40
  • 64
  • This post is worth a read - http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background – Dylan Jul 30 '14 at 22:47

2 Answers2

1

In an angular app, added DOM elements aren't automatically parsed. To do this you have to use $compile.

See:

https://stackoverflow.com/a/18157958/3893465 and https://docs.angularjs.org/api/ng/service/$compile

Community
  • 1
  • 1
jparonson
  • 322
  • 1
  • 4
0

What are the conditions that would make the controls be included or excluded? If there are a number of boolean variables in your controller that are used as flags, you can use the ngShow/ngHide or ngIf directives to show or hide them. Something like the following...

<form>
    <input type="text" ng-model="input.name" ng-show="input_enabled.name">
    <input type="text" ng-model="input.age" ng-hide="input_enabled.age">
    <input type="email" ng-model="input.email" ng-if="input_enabled.email">
    <input type="text" ng-model="input.phone" ng-disabled="input_enabled.phone">
</form>

And then in your controller...

$scope.input = {
    name: '',
    age: '',
    email: '',
    phone: ''
};

$scope.input_enabled = {
    name: true, /* this will show input.name */
    age: false, /* this will show input.age */
    email: false, /* this will hide imput.email */
    phone: true /* this will disable, but not hide, input.phone */
};
  • ngShow: creates and shows the element on truthy value
  • ngHide: creates and hides the element on truthy value
  • ngIf: creates the element on truthy value, destroys it on falsy
  • ngDisabled: creates the element, then adds the disabled attribute to it

This is a very basic overview, and not necessarily the way that you should do things, just an example of how they can be done. The AngularJS documentation, located here, is excellent. Angular is a great tool!

Jeff N
  • 430
  • 3
  • 5