【发布时间】:2015-12-28 11:42:45
【问题描述】:
当将函数传递到指令中,然后传递到嵌套的子指令中时,在子指令的范围内检查时始终认为该函数已定义,无论它是否在父指令中传递。
在处理嵌套指令时是否有更好的方法来传递函数指针或检查它们是否已定义。
<body ng-app="myApp">
<div ng-controller="myController">
<dir1"></dir1>
</div>
<script type="text/ng-template" id="dir1">
<div>
<dir2 fun="fun()"></dir2>
</div>
</script>
<script type="text/ng-template" id="dir2">
<div>{{fun()}}</div>
<div>{{funDefined()}}</div> <!-- always true-->
</script>
</body>
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.fun = function() {
alert("function");
};
});
app.directive('dir1', function() {
return {
scope: {
fun: '&'
},
templateUrl: 'dir1'
};
});
app.directive('dir2', function() {
return {
scope: {
fun: '&'
},
link: function(scope, elem, attrs) {
scope.funDefined = function() {
return angular.isDefined(attrs.fun);
};
},
templateUrl: 'dir2'
};
});
【问题讨论】:
-
好吧,但就 dir2 而言,它是定义的。调用者有责任提供正确的参数。
标签: javascript angularjs