如果不使用isoloted范围,如何访问指令及其模板内的控制器This
?
app.controller('ChildCtrl', function() {
this.name = "Name from children";
});
答案 0 :(得分:1)
简单地将其解析为controller as instance value
到您的指令范围内,例如 simple fiddle demo :
<div ng-controller="MyCtrl as ctrl">
Hello, <span simple-directive data="ctrl.name"></span>!
</div>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
this.name = 'Superhero';
});
myApp.directive('simpleDirective', function () {
return {
restrict: 'A',
scope: {
data: '='
},
template: '{{ data }}',
link: function (scope, elem, attrs) {
console.log(scope.data);
}
}
});
另一种方法是使用{strong> demo fiddle 中的controller:'MyCtrl as ctrl'
将控制器解析为指令。
Hello, <span simple-directive></span>!
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
this.name = 'Superhero';
});
myApp.directive('simpleDirective', function () {
return {
restrict: 'A',
controller:'MyCtrl as ctrl',
template: '{{ ctrl.name }}'
}
});
您也可以将孔控制器实例解析到范围内,并像在 demo fiddle 中一样访问它。
<div ng-controller="MyCtrl as ctrl">
Hello, <span simple-directive ctrl="ctrl"></span>!
<br />
<input type="text" ng-model="ctrl.name">
</div>
var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl', function ($scope) {
this.name = 'Superhero';
});
myApp.directive('simpleDirective', function () {
return {
restrict: 'A',
scope: {
ctrl: '='
},
template: '{{ ctrl.name }}',
link: function (scope, elem, attrs) {
}
}
});