简体   繁体   English

如何从Angular中的静态指令模板访问隔离的范围属性?

[英]How to access isolated scope property from static directive template in Angular?

Controller: 控制器:

app.controller('MainCtrl', ['$scope', function($scope) {
    $scope.temp = {
        'name': 'Test'
    };
}]);

Template: 模板:

<custom-field ng-model="temp.name">
    <md-input-container class="addon-menu">
        <label>Name</label>
        <input ng-model="ngModel" type="text" ng-focus="setLastFocusedElement($event)" />
    </md-input-container>
</custom-field>

Directive: 指示:

app.directive('customField', function($timeout) {
   return {
       restrict: 'E',
       scope: {
           ngModel: '='
       },
       link: function($scope, $element, $attrs) {
           console.log($scope.ngModel); // prints "test"
       }
   };
});

The problem is that once template is rendered, I can't see the value attached to input - it's empty, but I'm expecting to works, because inside link function it's printed correctly. 问题在于,一旦呈现了模板,我将看不到input附加的值-它为空,但是我希望它能正常工作,因为在link函数内部它可以正确打印。

You are trying to access the directive scope in your template as the controller's scope. 您正在尝试访问模板中的指令范围作为控制器的范围。 Move the markup inside the directive's template instead. 而是将标记移动到指令的模板内。

Directive: 指示:

app.directive('customField', function($timeout) {
return {
   restrict: 'E',
   scope: {
       ngModel: '='
   },
   link: function($scope, $element, $attrs) {
       console.log($scope.ngModel); // prints "test"
   },
   template: '<md-input-container class="addon-menu"><label>Name</label><input ng-model="ngModel" type="text" ng-focus="setLastFocusedElement($event)" /></md-input-container>'
};

Template: 模板:

<custom-field ng-model="temp.name"></custom-field>

You can also use separate html files as directive templates, which is good practise. 您也可以将单独的html文件用作指令模板,这是一个很好的实践。

Are you trying to see the value in controller? 您是否正在尝试查看控制器中的值?

Please try $parent.$scope to see if value exist. 请尝试$ parent。$ scope以查看值是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM