AngularJS指令在范围内创建空数组。

时间:2014-11-20 13:23:28

标签: angularjs

我创建了一个指令并以这种方式使用范围变量:

<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 .. 

我如何解决问题?

祝你好运。

3 个答案:

答案 0 :(得分:3)

尝试取出$scope.apply

.directive("createInstantsSinceBeginning", function() {
  return {
    scope: {
      daysnum: "=",
      tostore: "="
    },
    link: function(scope, element) {
      if (typeof scope.tostore == 'undefined') {
        scope.tostore = [];
      }
    }
  };
});

参见工作示例:http://plnkr.co/edit/OVsKcDebdNhxgCfdig4q?p=preview

答案 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 ..