我有市场'指令:
angular
.module('myModule')
.directive('market', [function () {
return {
restrict: 'EA',
template: '<div outcome="outcome" ng-click="onOutcomeClick()" ng-repeat="outcome in market.Outcomes">{{outcome.Odd}}</div>',
controller: ['$scope', function ($scope) {
$scope.market = {
Outcomes: [
{ Odd: 1 },
{ Odd: 2 },
{ Odd: 3 },
{ Odd: 4 },
{ Odd: 5 },
]
};
}],
link: function (scope, elem, attrs) {
}
}
}]);
其中包含许多结果&#39;指令:
angular
.module('myModule')
.directive('outcome', [function () {
return {
restrict: 'A',
scope: {
outcome: '='
},
controller: ['$scope', function ($scope) {
$scope.onOutcomeClick = function () {
console.log($scope.outcome.Odd);
};
}],
link: function (scope, elem, attrs) {
}
}
}]);
当我点击&#34;结果&#34;时,似乎有角度寻找&#34; onOutcomeClick&#34;在&#34;市场&#34;指令,但不是&#34;结果&#34;指示。 如何强制角度呼叫&#34; onOutcomeClick&#34;来自&#34;结果&#34;指令(范围在&#34;结果&#34;指令必须隔离)
jsfiddle示例:http://jsfiddle.net/dgjcf41d/5/ 我希望在示例中看到警报,但是失败
答案 0 :(得分:1)
答案是你不必在ng-click
指令中声明market
指令,你可以在outcome
指令中自己添加点击事件处理程序。
<强> FORKED DEMO 强>
<强>的Javascript 强>
市场指令
// remove the `ng-click` directive
.directive('market', [function () {
return {
// ....
template: '<div outcome="outcome" ng-repeat="outcome in market.Outcomes">{{outcome.Odd}}'</div>
// ...
};
});
结果指示
.directive('outcome', [function () {
return {
restrict: 'A',
scope: {
outcome: '='
},
link: function (scope, elem, attrs) {
elem.on('click', function() {
alert('outcome clicked: ' + scope.outcome.Odd);
});
}
}
}]);
答案 1 :(得分:0)
您已在ngClick
指令中定义market
。每个outcome
指令都有一个独立的范围(market
范围的子)。这就是ngClick
在onOutcomeClick
范围内查找market
的原因。
为outcome
指令定义模板,并将ngClick
放在那里。
angular.module('myModule', [])
.controller('myController', [function () { }])
.directive('market', [function () {
return {
restrict: 'EA',
template: '<div outcome="outcome" ng-repeat="outcome in market.Outcomes"><outcome outcome=outcome>{{outcome.Odd}}</outcome></div>',
controller: ['$scope', function ($scope) {
$scope.market = {
Outcomes: [
{ Odd: 1 },
{ Odd: 2 },
{ Odd: 3 },
{ Odd: 4 },
{ Odd: 5 },
]
};
}]
}
}])
.directive('outcome', [function () {
return {
restrict: 'E',
template: '<div ng-click="onOutcomeClick()" ng-transclude></div>',
transclude: true,
scope: {
outcome: '='
},
controller: ['$scope', function ($scope) {
$scope.onOutcomeClick = function () {
alert('outcome clicked: ' + $scope.outcome.Odd);
};
}]
}
}]);