Search code examples
angularjsionic-frameworkionic-view

How to run angular code snippet in Ionic framework


So I have this simple code in angular that works on jsfiddle as you can see by pressing Run code snippet:

function ContactController($scope) {
    $scope.contact = 0;

    $scope.add = function() {
        $scope.contact += 1;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="" ng-controller="ContactController">

    <button ng-click="add()">Add</button>

    <div>{{ contact }}</div>

</div>

But when I try to use it in my Ionic app, it doesn't work. This is my complete index.html file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
    <script src="js/controllers.js"></script>
    <script src="js/services.js"></script>
</head>

<body id="body">

<div ng-app="" ng-controller="ContactController">

    <button ng-click="add()">Add</button>

    <div> {{ contact }} </div>


</div>

<script>
    function ContactController($scope) {
        $scope.contact = 0;

        $scope.add = function() {
            $scope.contact+=1;
        }
    }
</script>

</body>
</html>

Can anyone please tell me what I need to include in index.html in order for angular to work?


Solution

  • yes you need to initialize your app. in your app.js file you should see

    angular.module('starter', ['ionic'])
    

    so in your index.html you have ng-app=""

    that needs to say

    ng-app="starter"
    

    You're html should look like this:

    <div ng-app="starter" ng-controller="ContactController">
    
        <button ng-click="add()">Add</button>
    
        <div> {{ contact }} </div>
    
    </div>
    

    right now nothing is being bootstrapped and angular is not being attached to the page.