不使用孤立范围时如何访问This
指令及其模板内的控制器?
app.controller('ChildCtrl', function() {
this.name = "Name from children";
});
不使用孤立范围时如何访问This
指令及其模板内的控制器?
app.controller('ChildCtrl', function() {
this.name = "Name from children";
});
简单地将其解析为controller as instance value
您的指令范围,就像在这个简单的小提琴演示中一样:
<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);
}
}
});
另一种方法是通过使用controller:'MyCtrl as ctrl'
like in this demo fiddle将您的控制器解析为指令。
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 }}'
}
});
您还可以将洞控制器实例解析到范围内并像在这个演示小提琴中一样访问它。
<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) {
}
}
});