这里的目标是有两个不同的指令,技术上是兄弟姐妹共享功能。我会用其中一个或,另一个里面没有一个。角度控制器继承范围问题
但是,第二条指令将具有第一条的所有功能并添加一些小的添加。因此,我希望从“Parent”指令继承到“Child”的功能。
我通过重新使用Child上的Parent的相同指令定义对象来实现此目的,但要更改的控制器/模板字段除外。
这一切都运行良好,直到我从我的ParentDirCtrl
打到观察者。由于某种原因,观察者似乎设置正确,观察mydir.obj1
,但不知何故内部观察者回调函数mydir.obj1
变得未定义。
我假设一些关于_.extend
/$controller
正在改变如何$scope
的工作所以mydir.obj1
没有在ParentDirCtrl
定义,但我不知道为什么会是这样。
angular.module('plunker', [])
// lodash
.constant('_', _)
.controller('MainCtrl', function($scope, $timeout) {
$scope.obj = {
name: 'John',
age: 30,
};
})
.controller('ParentDirCtrl', function($scope) {
var mydir = this;
mydir.doStuffInParent = function() {
alert('executed from the parent directive');
}
$scope.$watch('mydir.obj1', function() {
// ====================================
// ERROR
// Why is 'mydir.obj1' undefined when
// occupation is set?
// ====================================
mydir.obj1.occupation = 'Meteorologist';
});
})
.directive('parentDirective', parentDirective)
.directive('childDirective', function() {
// borrow the directive definition object from the parent directive
var parentDDO = parentDirective();
// uodate the template and controller for our new directive
parentDDO.template = [
'<div>',
'<p ng-click="mydir.doStuffInParent()">{{mydir.obj1.name}}</p>',
'<p ng-click="mydir.doStuffInChild()">{{mydir.obj1.age}}</p>',
'</div>'
].join('');
parentDDO.controller = function($scope, $controller, _) {
// extend 'this' with the Parent's controller
var mydir = _.extend(this, $controller('ParentDirCtrl', { $scope: $scope }));
mydir.doStuffInChild = function() {
alert("executed from the child directive");
};
};
return parentDDO;
});
// this will be moved to the top during declaration hoisting
function parentDirective() {
return {
restrict:'E',
scope: {},
bindToController: {
obj1: '=',
},
template: '<div>{{mydir.obj1}}</div>',
controller: 'ParentDirCtrl',
controllerAs: 'mydir',
};
}
如果它们基本相同,为什么不能通过设置属性来区分功能? – charlietfl
孩子将会有一些功能覆盖父母的功能,然后是父母不需要的功能。另外,它还会有一些观察者来查看父项中不存在的属性。这就是说,父母中的100%功能是儿童所需要的。需要很多条件来在单个指令中控制所有这些。 – diplosaurus
'var mydir'是'this'用来自父控制器的属性扩展的。我的理解是,这是从另一个控制器继承的方式。 – diplosaurus