Test Angularjs in a blank web-page without a html
Blogs20142014-06-25
Test Angularjs in a blank web-page without a html
I wrote a small script which can run at a blank web-page to test js codes, such as angularjs, pretty cool.
1. Dynamically load js library
Open a blank chrome (or firefox) page, and ‘F12’ to open web inspector(or firebug) window. In ‘Console’, copy the following to excute:
// load the library:
var angularjs='//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.16/angular.js',
jquery = '//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js';
var s = document.createElement('script');
s.setAttribute('src', jquery);
document.body.appendChild(s);
s = document.createElement('script');
s.src = angularjs;
document.getElementsByTagName('head')[0].appendChild(s);This will load the jQuery and Angularjs into the page, without a html file support.
2. Test codes after js launched
Right now I can test any codes any codes based on the above js files could be tested. E.g. an Angular ng-submit:
//1.clear up context in the page, and add 'ng-app' attribute at 'body' level:
$('body').empty().attr('ng-app', '');
//2. add new html in the page:
var html = '<form ng-submit="submit()" ng-controller="Ctrl">' +
' Enter text and hit enter:' +
' <input type="text" ng-model="text" name="text" />' +
' <input type="submit" id="submit" value="Submit" />' +
' <pre>list={{list}}</pre>' +
' </form>';
$('body').append(html);
//3. write a controller:
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if ($scope.text) {
$scope.list.push(this.text);
$scope.text = '';
}
};
}By the way, CSS also can be dynamic loaded:
var css = document.createElement('link');
css.href = 'main.css';
css.rel = 'stylesheet';
document.getElementsByTagName('head')[0].appendChild(css);