0

I´m learning about Providers. On a common controller I would use

modu.controller("thecontrol", [function()
{
this.something = "Hello";
]});

and on the HTML

<div ng-controller="thecontrol as ctrl">
{{ ctrl.something }}
</div>

But... I´m trying to the the same with this code and, I really could not, even when I tried all the ways I "know".

Here´s the code...

What I want? Use THIS instead of $scope

<div ng-app="myApp" ng-controller="showingName">

{{theNameIs}}

</div>



<script src="angular.js"></script>

<script>
var myApp = angular.module("myApp", []);


myApp.provider("showingName", function() {

    this.name = "Luis";

    this.$get = function() {
        var name = this.name;
        return {
            showName: function() {
                return name;
            }
        }
    };

    this.setName = function(name) {
        this.name = name;
    };
});


myApp.config(function(showingNameProvider){
    showingNameProvider.setName("Juan");
});



myApp.controller("showingName", function($scope, showingName)
{
$scope.theNameIs = showingName.showName();
});


</script>

And yes... It works, but I would like to know if it´s possible to do it with THIS.

Thanks!

Peter
  • 2,004
  • 2
  • 24
  • 57

1 Answers1

1

I think it's because when you don't name the controller, then the {{ }} has to be scope, since this and $scope can be different depending on the context. Say for instance in an ng-repeat, 1 controller yet essentially 2 scopes.

Name the controller like you did on the first, ctrl as showingName. Make the variable this.theNameIs and then use {{ ctrl.theNameIs }}

Also, personally I don't think you should name the controller and provider the same name, appreciate this is probably just an example.

More information on $scope and this:

'this' vs $scope in AngularJS controllers

Community
  • 1
  • 1
Shaun
  • 933
  • 9
  • 16
  • OMG! Thanks a lot! Yes...! My problem was around the "name" of the controller. Thanks =D – Peter Nov 19 '15 at 01:00