jserodio jserodio - 1 year ago 57
Javascript Question

Is there any way to remove angular attributes in HTML elements?

I was trying to understand how Angular.js works with a simple example.

<div ng-app="">
<p>Input something in the input box:</p>
<p>Name : <input type="text" ng-model="name" placeholder="Enter name here"></p>
<h1>Hello {{name}}</h1>

enter image description here

Is there any way that I can remove all of this, and just use angular on a separate JavaScript?

I mean to be able to do something like...

document.getElementsByTagName('input')[0].ng-model = "name";
document.getElementsByTagName('h1')[0].innerHTML = "Hello {{name}}";

Or is it mandatory to mesh with the HTML attributes?

I couldn't find any information related. Thanks in advance.

Answer Source

Like other MVVM frameworks, Angular is designed to be "obtrusive" (intermixed into the HTML), it's not really meant to be used unobtrusively. More in this question and its answers(s) on programmers.stackexchange.com: Is obtrusive JavaScript required to support a feature of AngularJS?

That doesn't mean you can't. You could use code to add the necessary attributes and such before letting Angular loose on your DOM. You'd do that by using manual initialization instead of the default automatic initialization, and putting your code filling in the attributes before the bootstrap call:

document.getElementsByTagName('input')[0].setAttribute("ng-model", "name");
document.getElementsByTagName('h1')[0].innerHTML = "Hello {{name}}";
// ...and so on...
angular.bootstrap(document, ['myApp']);

...but that's not how Angular is really meant to be used.