【问题标题】:Fire AngularJS directive on view load在视图加载时触发 AngularJS 指令
【发布时间】:2014-06-12 08:39:10
【问题描述】:

我有一个相当简单的应用程序。在这种情况下,用户单击 home.html 上的按钮以转到 map.html。在 map.html 上,一个 jQuery 插件(做成指令)应该在视图加载时触发。目前它没有。即使在用户到达 map.html 之前不会调用该指令,它也会在应用加载 (home.html) 时立即触发。

我也尝试使用Angular UI.Utils (jQuery Passthrough),但无济于事。

这是我的指令

directive('tfinderMap', function() {
    return {
       restrict: 'A',
       link: function(scope, element, attrs) {
           $(element).tfindermap(scope.$eval(attrs.tfinderMap));
       }
   };
});

jQuery 插件就是 $(element).tfinderMap({queryLimit: 3}),该插件可以在 here 找到 - 这是我创建的 Google Map API 插件。

此时我的控制器是空的...

.controller('MapCtrl', [function() {
}])

我的 ma​​p.html 视图 也是基本的...

<div ng-controller="MapCtrl">
    <div id="map" class="google-map-canvas" tfinder-map="{queryLimit: 3}"></div>

    <ul class="table-view" id="location-data">
        <!--plugin results get put into here-->
    </ul>

</div>

我的 index.html 加载了我所有的脚本(Angular 文件和插件代码),您可以单击导航项转到通过 $routeProvider 路由的 map.html(项目是以angular-seed 开头,仅供参考)


我查看了this question,但我认为提供的答案与我的问题无关。

那么有没有办法在我导航到 map.html 时重新加载整个页面,所以我的指令会触发,因为脚本也会重新加载?或者有没有办法重新初始化 map.html 视图和脚本(或指令)?

如上所述,我尝试过使用 jQuery Passthrough 以及 $scope.reload(),但没有成功...

最后我会提到,如果我手动刷新浏览器,我的指令会正常触发!

【问题讨论】:

    标签: jquery angularjs jquery-plugins angularjs-directive reload


    【解决方案1】:

    在分配tfinderMap 属性后尝试触发指令:

    attrs.$observe("tfinderMap",function(value){
     if(value){
       $(element).tfindermap(scope.$eval(attrs.tfinderMap));
     }
    })
    

    或者没有等待的超时:

    $timeout(function(){
            $(element).tfindermap(scope.$eval(attrs.tfinderMap));
    });
    

    【讨论】:

    • 是的!非常感谢!这一直让我发疯。我最终使用了您提供的第一个示例。但我也测试了第二个,它也有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2019-11-21
    相关资源
    最近更新 更多