在提供者的控制器上使用此替代$ scope

时间:2015-11-19 00:27:51

标签: angularjs angular-providers

我正在了解提供商。在一个公共控制器上,我会使用

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

和HTML

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

但是......我正试着用这段代码做同样的事情,我真的不能,即使我尝试了所有“我知道”的方式。

这是代码......

我想要什么?使用此而非$ 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>

是的......它有效,但我想知道是否可以用这个来做。

谢谢!

1 个答案:

答案 0 :(得分:1)

我认为这是因为当你没有为控制器命名时, {{}} 必须是范围,因为这和 $ scope 可能会有所不同,具体取决于在上下文中。比如说在ng-repeat,1个控制器,但基本上是2个范围。

将控制器命名为第一个, ctrl命名为showsName 。创建变量 this.theNameIs ,然后使用{ {ctrl.theNameIs}}

另外,我个人认为您不应该将控制器和提供商命名为相同名称,请注意这可能就是一个例子。

有关 $ scope 的更多信息:

'this' vs $scope in AngularJS controllers