angularjs – Angular $scope作为一个对象文字或多个$scope

前端之家收集整理的这篇文章主要介绍了angularjs – Angular $scope作为一个对象文字或多个$scope前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有以下控制器

angular.module('scopeExample',[])
    .controller('MyController',['$scope',function ($scope) {
        $scope.username = 'World';

        $scope.sayHello = function () {
            $scope.greeting = 'Hello ' + $scope.username + '!';
        };
}]);

有什么理由我不应该使用对象文字

angular.module('scopeExample',function ($scope) {
        $scope.viewmodel = {
            greeting: '',username: 'World',sayHello: function(){
                this.greeting = 'Hello ' + this.username + '!';
            }
        };
}]);

解决方法

您可以尝试使用此而不是$scope.
通过在视图中使用Controller As声明,您的视图中也会以点符号结束.

您的控制器代码最终可能如下所示:

angular.module('scopeExample',function () {
    var self = this;
    this.greeting = '';
    this.username = '';

    this.getName = function () {
        self.greeting = 'Hello ' + self.username + '!';
    };
}]);

在视图中使用Controller As声明将产生以下结果:

<div data-ng-controller="UserController as user">
       Hello {{ user.username }}
</div>

因此,在此示例中,您最终得到的代码较少,但您在视图中保留了点符号.

请注意,在Angular 1.2.0之前,Controller As功能不可用

猜你在找的Angularjs相关文章