2014-09-01 4 views
2

값이있는 속성이 있거나 없을 수도있는 사용자 지정 문이 있습니다. 사용자가 속성 값을 지정하지 않으면 기본값을 지정하려고합니다. 그러나 내가 할 때이 값은 내 범위에서 항상 null입니다.지시문에서 값이 작동하지 않는 경우

내가 뭘 잘못하고 있니?

지침 :

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: '@' 
    } 
    }; 
}); 

당신이 정말로 할당을 필요로하는 경우 기본값은 지침서 (Directive) 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

감사합니다. 컴파일 기능을 사용하지 않은 상태에서 –

+0

지시어 옵션을 모두 사용하십시오. 처음에는 복잡해 보이지만 그렇지 않습니다. – letiagoalves

-1

link() 메소드를 사용해야한다고 생각합니다. 그렇게하면 범위 변수가 null인지 확인하고 기본값을 할당 한 다음 수동으로 템플릿을 만들어 요소에 추가 할 수 있습니다. 범위 변수는 여전히 바인드되어 있습니다.

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); 
    } 
    }; 
});