Search code examples
javascriptangularjsangularjs-controlleras

angular "controller as syntax" "this" data


I dont understand what I am missing

I dont get result on html i think this problem managing with controllerAs syntax

note: I can see the result in console console.log(this.movie); - its from controller

app.js

var app = angular.module('mfApp',['ngRoute', 'appControllers']);

app.config(function($routeProvider){
    $routeProvider.
    when('/:detail',{
            templateUrl: 'template/detail.html',
            controller : 'detailCtrl' ,
            controllerAs: 'movieAs'
    }).otherwise({
         redirectTo: '/'
    });
});

controller.js

var mfControllers = angular.module('appControllers', []);


mfControllers.controller('detailCtrl', ['$scope', '$routeParams', 'appServices',  function($scope, $routeParams, appServices){
    this.movie = [];
    this.id = $routeParams.detail;
    appServices.homeSearch(this.id).success(function(response){
        this.movie = response;
        console.log(this.movie);  
        // Yes, I do get array result in console
    });

}]);

html - template/detail.html

My try

{{movieAs.Title}} 
{{movieAs.movie.Title}} 
{{movie.movieAs.Title}}  
{{movie.Title}} {{title}}

Solution

  • mfControllers.controller('detailCtrl', ['$scope', '$routeParams', 'appServices',  function($scope, $routeParams, appServices){
        var me = this;
        me.movie = [];
        me.id = $routeParams.detail;
        appServices.homeSearch(me.id).success(function(response){
            me.movie = response;
            console.log(me.movie);  
            // Yes, I do get array result in console
        });
    }]);
    

    EDIT

    In Javascript functions are stored as objects, so from your callbeck method inside succeess, you call this which refers to the method that you are running and not to the controller scope.

    It is best practice to store the reference to the controller in a variable which can be accessed by the callback methods. me is quite an arbitrary name but widely used to refer as the parent caller. https://github.com/johnpapa/angular-styleguide