我们试图在AngularJS指令中使用属性绑定,但是问题引起了错误,表示为
名称为
counterController
的控制器未注册。
我们希望将variable:firstcount
从counterController
传递到orderController
。单击按钮时,variable:firstcount
必须为增/减。
有人可以帮助我们解决错误吗?
(function(){
'use strict';
angular
.module('mainApp', []);
}());
<!DOCTYPE html>
<html ng-app="mainApp">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="angular.min.js"></script>
</head>
<body>
<div ng-controller='counterController as counter'>
<counter count="counter.firstcount"></counter>
</div>
<script src="app.js"></script>
<script src="counterController.js"></script>
<script src="orderController.js"></script>
<script src="counter.directive.js"></script>
</body>
</html>
(function () {
'use strict';
angular.module('mainApp', [])
.controller('orderController', orderController);
orderController.$inject = ['$scope'];
function orderController($scope) {
this.count=$scope.count;
console.log("Inside OrderController");
this.increment = function () {
this.count++;
}
this.decrement = function () {
this.count--;
}
};
}());
(function () {
'use strict';
angular.module('mainApp', [])
.controller('counterController', counterController);
counterController.$inject = ['$scope'];
function counterController($scope) {
var counter = this;
counter.firstcount = 10;
console.log("Inside Counter Controller");
counter.increment=function(){
counter.count++;
}
counter.decrement=function(){
counter.count--;
}
};
}());
(function () {
'use strict';
function counter() {
return {
restrict: 'E',
scope: {
count: '='
},
controller: 'orderController as order',
template: `
Counter: <input type="text" ng-model="order.count">
<button type="button" ng-click="order.increment()">Increment</button>
<button type="button" ng-click="order.decrement()">Decrement</button>
`
};
}
angular.module('mainApp')
.directive('counter', counter);
}());
删除控制器定义中的依赖项参数:
(function () {
'use strict';
̶a̶n̶g̶u̶l̶a̶r̶.̶m̶o̶d̶u̶l̶e̶(̶'̶m̶a̶i̶n̶A̶p̶p̶'̶,̶ ̶[̶]̶)̶
angular.module('mainApp')
.controller('orderController', orderController);
请注意,使用
angular.module('myModule', [])
将创建模块myModule
,并且覆盖任何名为myModule
的现有模块。使用angular.module('myModule')
检索现有模块。
有关更多信息,请参阅
您将继续定义应用程序模块,而不是每次都这样做:
angular.module('mainApp', [])
改为执行此操作:
angular.module('mainApp')
您实际上确实在counter.directive.js中遵循该模式。您应该只有:
angular.module('mainApp', [])
一旦在您的应用中,就有可能在app.js文件中。