简体   繁体   中英

Angular JS Binding not working

I am not sure what is going wrong in the following code - but it doesn't seems working. can anyone help?

<body ng-controller="MyFunction">
        <script>
            function MyFunction($scope) {
                $scope.author = {
                    'name':'Test',
                    'title': 'Mr',
                    'Job': 'SDE'
                }
            }
        </script>
       <h2> {{author.name}} </h2>
       <h2> {{author.title + " " + author.Job}} </h2> 
    </body>

Here you are. You are incorrect in structure of angularjs, I don't see the ng-app and wrong to declare controller:

 angular.module('app', []).controller('MyFunction', function($scope) { $scope.author = { 'name': 'Test', 'title': 'Mr', 'Job': 'SDE' } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app='app' ng-controller="MyFunction"> <h2> {{author.name}} </h2> <h2> {{author.title + " " + author.Job}} </h2> </body> 

Hope this helps.

There is several things wrong with your code. You are missing an ng-app declaration, you are missing a module to use for that declaration and you did not register your controller correctly. Your example in a working state:

 function authorInfoController() { this.author = { name: 'Amadeus Smith', title: 'Prof.', job: 'Super Senior Cloud Advisor Managment Consultant' }; } angular.module("myApp", []) .controller("AuthorInfoCtrl", authorInfoController); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"></script> <div ng-app="myApp" ng-controller="AuthorInfoCtrl as info"> <h2>{{info.author.name}}</h2> <h2>{{info.author.title + " " + info.author.job}}</h2> </div> 

If you are just learning angular, I recommend doing a good tutorial and reading a styleguide .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM