將 Controller 與 ControllerAs 語法一起使用
我們製作的 Controller 可以使用 controller as
語法進行例項化和使用。那是因為我們已經將變數直接放在控制器類而不是 $scope
上。
使用 controller as someName
是從 $scope
本身分離控制器。因此,不需要在控制器中注入$ scope 作為依賴項。
傳統方式:
// we are using $scope object.
app.controller('MyCtrl', function ($scope) {
$scope.name = 'John';
});
<div ng-controller="MyCtrl">
{{name}}
</div>
現在,使用 controller as
語法 :
// we are using the "this" Object instead of "$scope"
app.controller('MyCtrl', function() {
this.name = 'John';
});
<div ng-controller="MyCtrl as info">
{{info.name}}
</div>
如果在 JavaScript 中例項化類**,則可以執行以下操作:**
var jsClass = function () {
this.name = 'John';
}
var jsObj = new jsClass();
所以,現在我們可以用 jsObj
例項來訪問任何方法或屬性 jsClass
。
在 angular 中,我們做同樣型別的事情。我們使用控制器作為例項化的語法。