【问题标题】:Angular Animation Directive角度动画指令
【发布时间】:2015-10-20 21:38:01
【问题描述】:

我正在尝试编写一个 Angular 指令,该指令将为类似于 http://codepen.io/rachsmith/pen/BNKJme 的单词列表设置动画。但是,我需要从 json 文件加载文本,然后选择一个随机句子来应用动画。我有这部分工作,但无法访问指令的子元素。我假设这是因为在渲染元素之前调用了指令,但是使用 scope.$on($viewContentLoaded, function... 并没有产生任何影响。

我有 jQuery 和 Underscore 可用。

这是我的代码:

控制器

Data.sentences().then(function (response) {
    var sentences = response.data;
    $scope.sentence = _.sample(sentences);
});

查看

    <div class="rotator">
        <p>{{sentence.static}}</p>
        <text-rotator>
            <span class="word" ng-repeat="item in sentence.options">{{item}}</span>
        </text-rotator>
    </div>

指令

app.directive('textRotator', function () {
    return {
        restrict: 'E',
        link: function (scope, el, attrs) {
            var words = el.children('.word');
            //cannot access array of items with class of word
        }
    };
});

【问题讨论】:

  • 您是否设法让指令按您的意愿工作?

标签: angularjs animation directive


【解决方案1】:

您的假设是正确的,在执行指令的 link 函数时,ng-repeat-ed 单词 尚未在 DOM 中。 sentence 对象是异步获取的。 监听$viewContentLoaded 无济于事:这是ngRoute 模块在ngView 的内容加载时触发的事件。在一个摘要周期之后,由于模型的变化而更新了 DOM,此事件不会被触发。

实际上,我认为您正在给自己制造麻烦,因为数据可能(应该)作为参数传递给指令。子词元素将是指令的模板。我建议如下:

app.directive('textRotator', function () {
    return {
        restrict: 'E',
        scope: {
            options: '='   
        },
        templateUrl: 'words.html',
        link: // ...
    }
});

模板:

<text-rotator options="sentence.options"></text-rotator>

这个fiddle 可能会对您有所帮助。动画部分已被不透明度的简单切换所取代。此外,这些词在控制器中被模拟,你应该确保它们在路由/状态的定义中被路由器解析,否则你必须在指令中添加一个观察者。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-05
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多