我有以下Angular自定义指令代码:
模板(ReviewStandards.html)
<div class="review-standard" ng-repeat="standard in standards">
<button ng-click="mark(standard)">Mark Complete</button>
</div>
JS
app.directive("reviewStandards", function ($parse, $state) {
return {
restrict: "A",
templateUrl: function (elements, attrs) {
return "/Scripts/App/Directives/Templates/ReviewStandards.html";
},
transclude: false,
scope: {
standards: "="
},
replace: true,
link: function (scope, elem, attrs) {
scope.mark = function (standard) {
alert();
};
}
};
});
该指令用作:
<div review-standards standards="review.ReviewStandards"></div>
standards
只是standard
个对象的JSON数组。
问题是单击按钮时ng-click
没有触发该功能。范围是孤立的 - 这是与此有关还是按钮位于ng-repeat
?
答案 0 :(得分:5)
试试这个,“我只是删除代码中的替换”
watermelon //sum=9
orange, potatos //6+3=9
apple, tomato //4+5=9
apple, cherries //4+5=9
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
$scope.data = [{
name: "a"
},
{
name: "b"
}
];
});
app.directive("reviewStandards", function() {
var template = "<div class=\"review-standard\">" +
"<div ng-repeat=\"standard in standards\">" +
"{{standard.name}} " +
"<button ng-click=\"mark(standard)\">Mark Complete</button>" +
"<div><hr>" +
"</div>";
return {
restrict: "A",
transclude: false,
template: template,
scope: {
standards: "="
},
link: function(scope, elem, attrs) {
scope.mark = function(standard) {
console.log(standard)
};
}
};
});
答案 1 :(得分:2)
我会尝试一下解释为什么会发生这种情况。
使用 replace:true 时在范围继承方面存在问题,在模板中只有一个元素 ng-repeat 。
如果替换:false ,模板会在元素中使用指令粘贴元素,所以你会得到类似这样的内容
<div review-standards standards="review.ReviewStandards"> <!-- here isolated scope from review-standards directive -->
<div class="review-standard" ng-repeat="standard in standards"> <!-- here child scope created with ng-repeat -->
<button ng-click="mark(standard)">Mark Complete</button>
</div>
</div>
因此, ng-repeat 创建的子范围继承自隔离范围审查标准指令,并且所有来自隔离范围的属性都可用在儿童范围内。
当使用替换:true 时,模板替换元素与指令,你得到这样的东西
<div class="review-standard" ng-repeat="standard in standards" review-standards standards="review.ReviewStandards"> <!-- here child scope created with ng-repeat -->
<button ng-click="mark(standard)">Mark Complete</button>
</div>
在这种情况下最有趣的是,现在,子项从 ng-controller 继承了,但$parent
属性设置为已隔离范围审核标准指令。因此,在儿童范围内可用 ng-controller 范围内的所有属性,但隔离范围审查标准指令中的不
最简单的解决方法,如附近的答案所示,只需删除 replace:true
另一种方式:比特改变模板,像这样
<div>
<div class="review-standard" ng-repeat="standard in standards">
<button ng-click="mark(standard)">Mark Complete</button>
</div>
</div>
或者有点丑陋的解决方案:使用 $ parent 属性而不是希望继承
<div class="review-standard" ng-repeat="standard in $parent.standards">
<button ng-click="$parent.mark(standard)">Mark Complete</button>
</div>