Angular JS - Dependency Injection

Edit

  angular.module('MyApp', [])
.controller('MyController', MyController)

MyController.$inject = ['$scope']
function MyController($scope) {
$scope.check = function(){}
}

MyController是controller的构造函数,通过$inject成员指定需要inject的部分(类比于上图的cardProc)。Angular在调用构造函数创建controller的时候,会把预先为这一块HTML创建的$scope传入该构造函数。

%23%20Angular%20JS%20-%20Dependency%20Injection%0A@%28myblog%29%5Bangular%2C%20javascript%5D%0A%0A%0A%21%5BAlt%20text%7C600x0%5D%28./1503652625713.png%29%0A%21%5BAlt%20text%7C600x0%5D%28./1503652641792.png%29%0A%60%60%60%0A%20%20angular.module%28%27MyApp%27%2C%20%5B%5D%29%0A%20%20%20%20.controller%28%27MyController%27%2C%20MyController%29%0A%0A%20%20MyController.%24inject%20%3D%20%5B%27%24scope%27%5D%0A%20%20function%20MyController%28%24scope%29%20%7B%0A%20%20%20%20%24scope.check%20%3D%20function%28%29%7B%7D%0A%20%20%7D%0A%60%60%60%0AMyController%u662Fcontroller%u7684%u6784%u9020%u51FD%u6570%uFF0C%u901A%u8FC7%5C%24inject%u6210%u5458%u6307%u5B9A%u9700%u8981inject%u7684%u90E8%u5206%28%u7C7B%u6BD4%u4E8E%u4E0A%u56FE%u7684cardProc%29%u3002Angular%u5728%u8C03%u7528%u6784%u9020%u51FD%u6570%u521B%u5EFAcontroller%u7684%u65F6%u5019%uFF0C%u4F1A%u628A%u9884%u5148%u4E3A%u8FD9%u4E00%u5757HTML%u521B%u5EFA%u7684%5C%24scope%u4F20%u5165%u8BE5%u6784%u9020%u51FD%u6570%u3002