加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 06:47:55 所属栏目:安全 来源:网络整理
导读:假设我有以下控制器 angular.module('scopeExample',[]) .controller('MyController',['$scope',function ($scope) { $scope.username = 'World'; $scope.sayHello = function () { $scope.greeting = 'Hello ' + $scope.username + '!'; };}]); 有什么理由
假设我有以下控制器

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功能不可用

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读