我创建了一个指令并以这种方式使用范围变量:
<div data-create-instants-since-beginning data-daysnum="daysnum" data-tostore="tostore">
我想在tostore未定义时将其设置为空数组,但遗憾的是这不起作用。
.directive("createInstantsSinceBeginning", function () {
return {
scope: {
daysnum: "=",
tostore: "="
},
link: function ($scope, element) {
if (typeof $scope.tostore == 'undefined') {
$scope.$apply(function () {
$scope.tostore = [];
});
}
// other code ..
我如何解决问题?
祝你好运。
答案 0 :(得分:3)
尝试取出$scope.apply
.directive("createInstantsSinceBeginning", function() {
return {
scope: {
daysnum: "=",
tostore: "="
},
link: function(scope, element) {
if (typeof scope.tostore == 'undefined') {
scope.tostore = [];
}
}
};
});
答案 1 :(得分:1)
只需在指令的控制器中执行:
app.directive('createInstantsSinceBeginning',function(){
return {
scope: {
daysnum: "=",
tostore: "="
},
controller: function($scope){
if ( $scope.tostore === undefined )
$scope.tostore = [];
}
}});
答案 2 :(得分:1)
最短路:
.directive("createInstantsSinceBeginning", function () {
return {
scope: {
daysnum: "=",
tostore: "="
},
link: function ($scope, element) {
$scope.tostore = $scope.tostore || [];
}
// other code ..