Javascript 如何访问指令链接中的控制器功能?
如何从指令链接访问指令控制器功能?传递给链接的Bellow控制器为空,我想在其中使用show()hide()函数 我目前的指示:Javascript 如何访问指令链接中的控制器功能?,javascript,angularjs,angularjs-directive,angularjs-scope,Javascript,Angularjs,Angularjs Directive,Angularjs Scope,如何从指令链接访问指令控制器功能?传递给链接的Bellow控制器为空,我想在其中使用show()hide()函数 我目前的指示: app.directive('showLoading', function() { return { restrict: 'A', // require: 'ngModel', scope: { loading: '=showLoading' }, controller: function($scope, $el
app.directive('showLoading', function() {
return {
restrict: 'A',
// require: 'ngModel',
scope: {
loading: '=showLoading'
},
controller: function($scope, $element) {
return {
show: function() {
alert("show");
},
hide: function() {
alert("hide");
}
};
},
link: function($scope, $element, $attrs, controller) {
$scope.$watch('loading', function(bool) {
if (bool) {
controller.show();//undefined
} else {
controller.hide();
}
});
}
};
});
控制器函数内部存在某种问题 这里的代码运行良好
app.directive('showLoading', function() {
return {
restrict: 'AE',
// require: 'ngModel',
scope: {
loading: '=showLoading'
},
controller: function($scope, $element) {
$scope.show = function() {
alert("show");
},
$scope.hide = function() {
alert("hide");
}
},
link: function($scope, $element, $attrs) {
$scope.$watch('loading', function(bool) {
if (bool) {
$scope.show();//undefined
} else {
$scope.hide();
}
});
}
};
});
在范围上发布可以奏效,但不是最佳做法,因为它“污染”了范围。与自己的控制器通信的正确方式是
要求它-然后它将作为链接
功能的参数以及其他要求的指令可用
另一个问题是如何在控制器上公开函数-这是通过使用this.someFn
,而不是通过返回对象来实现的
app.directive('showLoading', function() {
return {
restrict: 'A',
require: ['ngModel', 'showLoading'], // multiple "requires" for illustration
scope: {
loading: '=showLoading'
},
controller: function($scope, $element) {
this.show = function() {
alert("show");
};
this.hide = function() {
alert("hide");
};
},
link: function($scope, $element, $attrs, ctrls) {
var ngModel = ctrls[0], me = ctrls[1];
$scope.$watch('loading', function(bool) {
if (bool) {
me.show();
} else {
me.hide();
}
});
}
};
});
感谢您描述了当有额外的必需控制器时如何访问指令控制器。这个答案被标记为一个解决方案,这真是小题大做。“新开发人员”发布的消息实际上要好得多。