Angularjs 角度$scope作为一个对象文字或多个$scope';s
假设我有以下控制器Angularjs 角度$scope作为一个对象文字或多个$scope';s,angularjs,Angularjs,假设我有以下控制器 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', [])
.controller('MyController', ['$scope', function ($scope) {
$scope.viewModel = {
greeting: '',
username: 'World',
sayHello: function(){
this.greeting = 'Hello ' + this.username + '!';
}
};
}]);
为什么要向HTML添加更多代码。您必须使用{{viewModel.username}访问特定变量 为了避免这种情况,您也可以这样编写代码
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function ($scope) {
var viewModel = {
greeting: '',
username: 'World',
sayHello: function(){
this.greeting = 'Hello ' + this.username + '!';
}
};
angular.extend($scope, viewModel);
}]);
但是我认为第一种方法比这个符号更容易阅读。但使用任何一种方法都不会造成重大伤害 我个人更喜欢使用对象文字,而不是绑定一切$scope。 这是可管理的良好做法
angular.module('scopeExample', [])
.controller('MyController', ['$scope', function ($scope) {
var viewModel = {
greeting: '',
username: 'World'
};
viewModel.sayHello = function () {
this.greeting = 'Hello ' + this.username + '!';
};
$scope.viewModel = viewModel;
}]);
您可以尝试使用
this
而不是$scope
。
通过在视图中使用控制器作为声明,您也将在视图中使用点符号
您的控制器代码最终可能会如下所示:
angular.module('scopeExample', [])
.controller('MyController', function () {
var self = this;
this.greeting = '';
this.username = '';
this.getName = function () {
self.greeting = 'Hello ' + self.username + '!';
};
}]);
<div data-ng-controller="UserController as user">
Hello {{ user.username }}
</div>
在视图中将控制器用作声明将导致以下结果:
angular.module('scopeExample', [])
.controller('MyController', function () {
var self = this;
this.greeting = '';
this.username = '';
this.getName = function () {
self.greeting = 'Hello ' + self.username + '!';
};
}]);
<div data-ng-controller="UserController as user">
Hello {{ user.username }}
</div>
你好{{user.username}
因此,在本例中,代码更少,但在视图中保留了点符号
请注意,控制器As功能在Angular 1.2.0之前不可用我也认为第一个更容易阅读,但这可能只是因为我使用的示例。我经常使用对象文字,因为这是组织代码的好方法。但我从来没有在angular编码示例中真正看到它大多数angularJs开发人员通常来自Javascript背景。所以我认为他们采用了第一种方式,这就是为什么文档中包含类似于示例1的代码。但每个人都有自己的偏好。啊,这是一种很好的方式。除此之外,ControllerAs语法是每个官方视频片段中显示从angular 1.x应用程序转换为angular2应用程序的第一步,因此使用ControllerAs将使您更接近于兼容开箱即用,是内部angular团队的首选语法。