到目前为止我的代码:
.directive('ngSpreadsheet', function () {
return {
restrict: 'EA',
scope: {
curpart: '='
},
template: '<div id="dataTable" class="dataTable"></div>',
controller: SpreadsheetController,
link: function (scope, element, attrs) {
scope.$watch('curpart', function (val) {
console.log('curpart value changed, new value is: ' + val);
// here i want to call a function of the SpreadsheetController
// or is there a better way, executing stuff when an attribute changed?
});
}
}
})
var SpreadsheetController = (function () {
...
SpreadsheetController.prototype.curPartChanged = function () {
console.debug('curPartChanged');
};
})();
答案 0 :(得分:1)
如果您想在指令中引用控制器,则需要您自己的指令。请参阅:http://jsfiddle.net/7LnrZ/22/
var mod = angular.module("myapp", []);
mod.controller("SimpleCtrl", function ($scope) {
var part = {};
part.curpart = 1;
$scope.part = part;
$scope.increasePart = function () {
part.curpart++;
}
});
var SpreadsheetController = function () {
console.log("Instantiating SpreadsheetController");
}
SpreadsheetController.prototype.curPartChanged = function () {
console.log('curPartChanged');
}
mod.directive("ngSpreadsheet", function ($window) {
return {
restrict: 'EA',
scope: {
curpart: '='
},
require: "ngSpreadsheet",
template: '<div id="dataTable" class="dataTable"></div>',
controller: SpreadsheetController,
link: function (scope, element, attrs, ctrl) {
scope.$watch('curpart', function (val) {
console.log('curpart value changed, new value is: ' + val);
ctrl.curPartChanged();
});
}
}
});
编译指令的顺序:
答案 1 :(得分:1)
link
函数的第四个参数是控制器;我建议以这种方式访问。
link: function (scope, element, attrs, controller){
//...
controller.curPartChanged(...);
//...
}
我似乎无法直接链接到锚点,但look in this doc用于LINK
上的部分。您可以搜索“控制器实例,如果元素上至少有一个指令定义控制器”,则可以找到确切的部分。
修改强>
如果您想观看指令的属性,我会考虑$observe
函数,它与$watch
非常相似。前往this SO post了解详情。
答案 2 :(得分:0)
指令与托管它的控制器之间的通信应通过事件调用进行。 scope.$emit
会发送此类事件,而$scope.$on
会捕获另一方的事件。
.directive('ngSpreadsheet', function () {
return {
restrict: 'EA',
scope: {
curpart: '='
},
template: '<div id="dataTable" class="dataTable"></div>',
controller: function($scope){
$scope.$on('curpart.change',function(data){
console.log('curpart changed.. the new value is: ',data);
}),
link: function (scope, element, attrs) {
scope.$watch('curpart', function (evt,val) {
console.log('curpart value changed, new value is: ' + val);
scope.$emit('curpart.change',val);
});
}
}
});