[英]AngularJS cannot access directive scope inside controller
Directive scope values(initialValue and title) are undefined
in my controller function - counterController. 指令范围值(initialValue和title)在我的控制器功能-counterController中
undefined
。 It prints initialValue if I define it like {{ counterCtrl.initialValue }}
in app_counter.directive.html
, but undefined
in counterController
function. 如果我在
app_counter.directive.html
像{{ counterCtrl.initialValue }}
那样定义它,它将打印initialValue,但在counterController
函数中undefined
counterController
。
app_counter.directive.js app_counter.directive.js
'use strict';
module.exports = function (app) {
app.directive('appCounter', appCounter)
};
function appCounter() {
let directive = {
restrict: 'EA',
template: require('./app_counter.directive.html'),
scope: {
initialValue: '=',
title: '@'
},
controller: counterController,
controllerAs: 'counterCtrl',
bindToController: true
};
return directive;
}
function counterController() {
let vm = this;
vm.counter = vm.initialValue;
vm.increment = increment;
vm.decrement = decrement;
function increment() {
vm.counter += 1;
}
function decrement() {
vm.counter -= 1;
}
}
app.js app.js
'use strict';
const angular = require('angular');
const app = angular.module('app', []);
require('./app_counter/app_counter.directive')(app);
app_counter.directive.html app_counter.directive.html
<div class="counter">
<div>Current value {{counterCtrl.title}}: {{ counterCtrl.counter }}</div>
<button type="button" ng-click="counterCtrl.decrement()">Decrement</button>
<button type="button" ng-click="counterCtrl.increment()">Increment</button>
</div>
index.html 的index.html
<div id="app" ng-app="app">
<app-counter title="hello" initial-value="10"></app-counter>
</div>
You need to access them with $scope
(as they are) inside your controller instead using your controller instance object ( this
) directly. 您需要在控制器内使用
$scope
(按原样)访问它们,而不是直接使用控制器实例对象( this
)。
function counterController($scope) {
let vm = this;
vm.counter = $scope.initialValue;
vm.increment = increment;
vm.decrement = decrement;
function increment() {
vm.counter += 1;
}
function decrement() {
vm.counter -= 1;
}
}
>> Demo fiddle >> 演示小提琴
You can achieve the same by using bindToController
which is available since AngularJS v1.3: 您可以使用从AngularJS v1.3开始可用的
bindToController
来实现相同的bindToController
:
myApp.directive('myDirective', function () {
return {
restrict: 'A',
scope: true,
controllerAs: 'counterCtrl',
bindToController: {
initialValue: '='
},
controller: function () {
this.$onInit = function () {
let vm = this;
vm.counter = vm.initialValue;
vm.increment = increment;
vm.decrement = decrement;
function increment() {
vm.counter += 1;
}
function decrement() {
vm.counter -= 1;
}
};
}
}
});
>> Demo fiddle >> 演示小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.