2013-08-05 6 views
0

내 설정을 설명한 후에 내 질문은 굵게 표시됩니다.AngularJS Odd 지시어 범위 동작

index.html을

<div ng-controller="MyCtrl"> 
    <user-picker placeholder="Type a name..."></user-picker> 
</div> 

설정 :

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

컨트롤러 :

ctrls.controller('MyCtrl', function($scope) { 
    $scope.foo = 'this is a foo'; 
}); 

지침 :

directives.directive('userPicker', function() { 
    return { 
    restrict: 'E', 
    replace: true, 
    scope: { 
     placeholder: '@' 
    }, 
    templateUrl: 'file.html', 
    link: function postLink($scope, ele, attrs) { 
     console.log($scope); 
     console.log('[ng] Scope is: '); 
     console.log($scope.placeholder); 
     console.log($scope.$parent.foo); 
    } 
}); 

file.html과 (지시자) :

<span> 
    <input placeholder="{{placeholder}}" type="text"> 
</span> 

그래서, 일반적으로 작동하고 끝낼 싶은 :

<span placeholder="Type a name..."> 
    <input placeholder="Type a name..." type="text"> 
</span> 

placeholder 속성이 제대로 해결됩니다.

이것을 수행하는 것이 올바른 방법입니까? 속성은 두 곳에서 끝납니다.

왜 이상한 행동 : 두 번째로 나는 console.log($scope)의 결과에 당황하고 있습니다. 콘솔 출력은 $scope 오브젝트에 정확하게 설정된 placeholder 속성을 표시합니다. 그러나 여전히 매우 다음 console.log($scope.placeholder) 문은 "정의되지 않음"을 반환합니다. 콘솔 출력에 속성이 설정 되었음이 명확하게 표시되면 어떻게 가능합니까?

  • 이동 또는 아이 <input> 태그에 아래로 부모로부터 placeholder 속성을 복사

    내 목표는.

  • 연결 함수 내에서 템플릿 범위에 액세스해야합니다.
  • 이 지시문이 들어있는 컨트롤러 MyCtrl 컨트롤러를 참조하십시오.

위에 언급 된 이상한 행동이 발생할 때까지 나는 거의 거기에있었습니다. 어떤 생각이라도 감사합니다.

+1

일부 HTML

<script type="text/ng-template" id="file.html"> <span> <input placeholder="{{placeholder}}" type="text"/> </span> </script> <body ng-app="app"> <div ng-controller="MyCtrl"> <user-picker placeholder="Type a name..."></user-picker> </div> </body> 

일부 JS

var app = angular.module('app', ['app.directives', 'app.controllers']); var directives = angular.module('app.directives', []); var ctrls = angular.module('app.controllers', []); ctrls.controller('MyCtrl', function ($scope) { $scope.foo = 'this is a foo'; }); directives.directive('userPicker', function() { return { restrict: 'E', replace: true, scope: { placeholder: '@' }, templateUrl: 'file.html', link: function postLink($scope, ele, attrs) { console.log($scope); console.log('[ng] Scope is: '); console.log(attrs["placeholder"]); console.log($scope.$parent.foo); } } }); 

바이올린. 콘솔의 이상 함은 앵글 러가 비동기식 물건들과 관련이 있다는 것입니다. http : // stackoverflow.com/questions/16571003/javascript-console-log-displays-same-same-object에 다른 값 – jdp

+0

음, 흥미 롭습니다. 자식을 복사하지 않고 속성을 하위로 이동하는 방법이 있는지 알고 있습니까? (위와 같이 끝났습니다) – vcardillo

답변

1

대신이 범위를 읽으려고 시도하면 attrs가 작동하는 것을 읽을 수 있습니까?

당신이 바로 지금까지 내가 말할 수있는 그 일을하고

http://jsfiddle.net/Rfks8/

+0

맞아, 그게 효과가있다. 왜 내가 그런 생각을하지 않았는지 모르겠다. 어쨌든, 고마워요! :) – vcardillo