2014-09-01 31 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); 
    } 
    }; 
});