無作用域的控制器
使用前提:作用域不復雜、無需繼承、無需控制器間通信。
如下就是一個無作用域控制器:
<!DOCTYPE html> <html ng-app="exampleApp"> <head> <title>Controllers</title> <script src="https://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <link href="https://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <script> var app = angular.module("exampleApp", []) .controller("simpleCtrl", function () { this.dataValue = "Hello, Adam"; this.reverseText = function () { this.dataValue = this.dataValue.split("").reverse().join(""); } }); </script> </head> <body> <p class="well" ng-controller="simpleCtrl as ctrl"> <h4>Top Level Controller</h4> <p class="input-group"> <span class="input-group-btn"> <button class="btn btn-default" type="button" ng-click="ctrl.reverseText()">Reverse</button> </span> <input class="form-control" ng-model="ctrl.dataValue"> </p> </p> </body> </html>
你可能已經發現瞭它和一般控制器之間的區別
1. 未對$scope造成依賴,而是用js的this關鍵字定義瞭自己的數據
2. 視圖中訪問時,需用如下方式訪問<要應用的控制器> as <變量名>
3. 使用控制器中數據時:<數據名>.<控制器中變量>