【问题标题】:AngularJS Odd Directive Scope BehaviorAngularJS 奇数指令作用域行为
【发布时间】:2013-08-05 01:21:31
【问题描述】:

在描述了我的设置后,我的问题以粗体显示。

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) 语句仍返回“未定义”。当控制台输出清楚地显示属性已设置时,这怎么可能?

我的目标是:

  • placeholder 属性从父级移动或复制到子级&lt;input&gt; 标记。
  • 可以从链接函数中访问模板范围。
  • 引用该指令所在的父 MyCtrl 控制器。

我几乎就在那里,直到我遇到了上面提到的奇怪行为。任何想法表示赞赏。

【问题讨论】:

  • 据我所知,你做得对。控制台的怪异与 Angular 在幕后所做的异步工作有关。 stackoverflow.com/questions/16571003/…
  • 嗯,很有趣。你知道是否有办法将属性向下移动到孩子身上,而不是复制它们(就像我上面所说的那样)。

标签: javascript angularjs


【解决方案1】:

读取 attrs 是否有效,而不是尝试从范围内读取此内容?

一些 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://jsfiddle.net/Rfks8/

【讨论】:

  • 你是对的,这确实有效。我不知道为什么我没有想到这一点。无论如何,谢谢你! :)
猜你喜欢
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 2018-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多