Thursday, June 12, 2014

Angular Directives Part 2 - One HTML shows off basic AngularJS

No need for a folder tree full of files just to show off AngularJS. Just one HTML file is all you need.
<html ng-app="app" ng-cloak ng-controller="controller1">
<head>
    <title ng-bind="title"></title>

    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

</head>
<body>
    <p ng-bind="title"></p>
    <span my-sample></span>

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>

    <script>
        angular.module('app', []);

        angular.module('app').run(['$q', '$rootScope', function ($q, $rootScope) {
            $rootScope.title = 'My application title';
        }]);

        angular.module('app').controller('controller1', ['$scope', 'factory1', function ($scope, factory1) {
            $scope.title = factory1.getTitle();
        }]);

        angular.module('app').factory('factory1', ['$rootScope', '$http', function ($rootScope, $http) {
            var getTitle = function() {
                return $rootScope.title;
            };

            return {
                getTitle: getTitle
            };
        }]);

        angular.module('app').directive('mySample', ['$compile', function ($compile) {
            return {
                restrict: 'A', // <-- default, doesn't need to be specified.
                link: function (scope, element, attrs, controller) {
                    var markup = "<input type='text' ng-model='sampleData' /> {{sampleData}}<br/>";
                    angular.element(element).html($compile(markup)(scope));
                }
            };
        }]);

    </script>
</body>
</html>

No comments: