What's the difference between these 2 Angular code snippets?

This question already has an answer here:

  • 'this' vs $scope in AngularJS controllers 7 answers

  • Snippet A is not working most likely because of how the controller is being attached. I am taking a wild guess here.

    Where you add ng-controller it should probably look something like:

     <body ng-controller="dishDetailController as dish">
    

    Where as you might have this instead:

     <body ng-controller="dishDetailController">
    

    Might not be the body tag could be a div or something.

    And to make more sense of it inside the snippet A controller try:

    var app = angular.module('confusionApp',[]);        
    app.controller('dishDetailController', function() {
    
        this = {//attributes here}
    
    });
    

    Otherwise you might have to write: {{dish.dish.stuff}} inside the template.


    The second snippet (B) is more or less straight out of the documentation https://docs.angularjs.org/guide/controller and is most likely what you are looking for.

    In Snippet A, assigning a value via this will apply the value directly to the controller itself. This will make it very difficult to access in other contexts, and is most likely not what you want.

    Conversely, Snippet B is leveraging the dependency injection provided by AngularJS to ensure that the proper scope is injected into the method. $scope has a much more complicated lifecycle, but the important thing to note is that this will make dish available outside the context of your controller, such as in an HTML template.

    If you need more details, this guy has a way better answer: 'this' vs $scope in AngularJS controllers


    chech this code it is working 
    
    <div ng-app='confusionApp' ng-controller='dishDetailController' class="media-body">
    <h2 class="media-heading">{{dish.name}}
    <span class="label label-danger">{{dish.label}}</span>
    <span class="badge">{{dish.price}}</span></h2>
    <p>{{dish.description1}}</p>
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js"></script>
    <script type="text/javascript">
    
    var app = angular.module('confusionApp',[]);
    app.controller('dishDetailController', function($scope) {
    
    var dish={ label:'name',name:'afzal',price:'10',description1:'this is the price'};
    
    $scope.dish = dish;
    });
    </script>
    
    链接地址: http://www.djcxy.com/p/77794.html

    上一篇: 在POST请求中使用这个vs $ scope

    下一篇: 这两个Angular代码片段有什么区别?