在模块中,控制器可以从外部控制器继承属性:
var app = angular.module('angularjs-starter', []);
var ParentCtrl = function ($scope, $location) {
};
app.controller('ChildCtrl', function($scope, $injector) {
$injector.invoke(ParentCtrl, this, {$scope: $scope});
});
Run Code Online (Sandbox Code Playgroud)
示例:死链接:http://blog.omkarpatil.com/2013/02/controller-inheritance-in-angularjs.html
模块内的控制器也可以继承兄弟姐妹吗?
var app = angular.module('angularjs-starter', []);
app.controller('ParentCtrl ', function($scope) {
//I'm the sibling, but want to act as parent
});
app.controller('ChildCtrl', function($scope, $injector) {
$injector.invoke(ParentCtrl, this, {$scope: $scope}); //This does not work
});
Run Code Online (Sandbox Code Playgroud)
第二个代码不起作用,因为$injector.invoke需要一个函数作为第一个参数,并且找不到引用ParentCtrl.
对于一个我无法看透的问题,我已经被困了一天.
我在users.js.coffee文件中有以下代码:
app = angular.module("app", ["ngResource"])
app.config ['$routeProvider', '$locationProvider', ($routeProvider, $locationProvider) ->
$locationProvider.html5Mode(true)
$routeProvider.when('/users/:id', {templateUrl: '/users/:id.json', controller: UserCtrl})
$routeProvider.when('/users/:id/videos', {templateUrl: '/users/:id/videos.json', controller: UserCtrl})
]
app.factory "User", ["$resource", ($resource) ->
$resource("/users/:id", {id: "@id"}, {
show: {method: "GET"},
videos: {method: "GET", isArray:true}
})
]
@UserCtrl = ["$scope", "$location", "$route", "http", "$routeParams", "User", ($scope, $location, $route, $http, $routeParams, User) ->
console.log($location)//LocationUrl {$$parse: function, $$compose: function, $$rewriteAppUrl: function, $$protocol: "http", $$host: "localhost"…}
console.log($route)//Object {routes: Object, reload: function}
console.log($routeParams)//Object {}
]
Run Code Online (Sandbox Code Playgroud)
为什么$ routeParams是一个空对象?如果我在视图中调用$ route.current.params,它会显示相应的参数.但不是在控制器中.更重要的是,我不能在控制器中调用$ route.current.params,因为尚未定义"current".