2014-09-01 63 views
2

我有一个自定义指令,它可能有也可能没有带值的属性。如果用户没有为该属性指定值,我想分配一个默认值。但是,当我这样做时,我的示波器上的值始终为零,如下所示:Plunkr为指令中的作用域赋值不起作用

我在做什么错了?

指令:

var app = angular.module('app', []); 

app.directive('variable', function(){ 
    return { 
    restrict: 'E', 
    replace: true, 
    template: '<h2>Directive value: {{ test }}</h2>', 
    scope: { 
    test: '@' 
    }, 
    controller: function($scope){ 
    $scope.test = 'code assignment'; 
    } 

    }; 
}); 

HTML:

<!DOCTYPE html> 
<html> 

    <head> 
    <link rel="stylesheet" href="style.css"> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script> 
    <script src="script.js"></script> 
    </head> 

    <body ng-app="app"> 
    <variable></variable> 
    <variable test="html assignment"></variable> 
    </body> 

</html> 

回答

2

前的模板与指令建立的$scope.test分配正在发生属性你逝去的,因为你没有宣布任何test属性,该指令以$scope.test作为undefined呈现。

如果您只是想要一个默认值,您应该执行以下操作,而不需要定义控制器,从而使代码更清晰和更小。

app.directive('variable', function(){ 
    return { 
    restrict: 'E', 
    replace: true, 
    template: '<h2>Directive value: {{ test || "default value" }}</h2>', 
    scope: { 
    test: '@' 
    } 
    }; 
}); 

看到这个working demo

如果你真的需要到默认值分配给指令的scope可以使用compile功能如下:

app.directive('variable', function() { 
    return { 
    restrict: 'E', 
    replace: true, 
    template: '<h2>Directive value: {{ test }}</h2>', 
    scope: { 
     test: '@' 
    }, 
    compile: function(element, attrs) { 
     if (!attrs.test) { 
     attrs.test = 'default value'; 
     } 
    } 
    }; 
}); 

看到这个working demo

+1

感谢勒蒂亚,那正是我以后的样子!还没有使用编译功能 – 2014-09-01 23:58:51

+0

玩弄所有指令选项。起初看起来很复杂,但事实并非如此。 – letiagoalves 2014-09-02 21:05:29

-1

我相信你需要使用link()方法。这样你就可以检查范围变量是否为空并分配一个默认值,然后手动创建模板并将其添加到元素中。请注意,范围变量仍然是绑定的。

app.directive('variable', function(){ 
    return { 
    restrict: 'E', 
    replace: true, 
    scope: { 
    test: '@' 
    }, 
    link: function(scope, element) { 

    if(scope.test === null) { 
     scope.test = 'default value'; 
    } 

    var template = "<h2>Directive value: {{ test }}</h2>"; 

    element.html(template); 
    } 
    }; 
});