jquery - Angular : ng:include for current template and scope?

标签 jquery angularjs

我是 Angular 的新手,但我已经在 google 上搜索了几个小时,似乎无法弄清楚我做错了什么......我试图解决的问题是在之后执行一些 jQuery 的能力部分已经加载。我找到了这篇文章:http://blog.ruedaminute.com/2012/02/angular-js-applying-jquery-to-a-loaded-partial/ ,它解释了如何使用 ng:include 而不是 ng:view,但它不起作用 - 模板没有被包含,更不用说执行 onload 了。

index.html:

<!DOCTYPE html>
<html ng-app="shorelinerealtors">
<head>
    <meta charset="UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="/lib/angular.js"></script>
    <script src="/lib/angular-resource.js"></script>
    <script src="/js/app.js"></script>
    <script src="/js/controllers.js"></script>
    <link rel="stylesheet" href="/css/style.css">
    <title>Shoreline Realtors</title>
</head>
<body>
<!--It works fine using ng:view, but of course no onload option-->
<!-- <ng:view></ng:view> -->
<!--This apparently does nothing... no hello world, no alert -->
<ng:include src="$service('$route').current.template" scope="$service('$route').current.scope" onload="init()"></ng:include>
</body>
</html>

住宅.html

<h2>{{hello}}</h2>

Controller .js

function ResidentialListCtrl($scope) {
    $scope.hello = "Hello World!";
    this.init = function() {
        alert("hello");
    };

}

app.js

angular.module('shorelinerealtors', ['listingsServices']).
    config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/listings/residential', {templateUrl: '/partials/residential.html', controller: ResidentialListCtrl}).
            otherwise({redirectTo: '/listings/residential'});
    }]);

更新: 我创建了一个jsfiddle:http://jsfiddle.net/xSyZX/7/为了这。它适用于 ngView,但不适用于 ngInclude。我需要做一些事情来在全局范围内定义 $service 吗?

最佳答案

如果您想在加载/处理页面上的元素时使用 JQuery 来实现这些元素,那么“Angular 方式”就是创建一个自定义指令来让 jQuery 为您工作。 Controller 不应该执行 DOM 操作,并且 onload 功能实际上是为该包含设置的“业务”逻辑。

下面是一个指令示例,该指令在处理某些元素后立即将其应用到某些元素:

app.directive('moveRightOnClick', function() {
    return {
       restrict: 'A',
       link: function(scope, elem, attr, ctrl) {
           //elem is a jquery object if JQuery is present.
           elem.click(function() {
              $(this).animate({ 'left': '+=20' }, 500);
           });
       }
    };
});

以下是您如何使用它。

<div move-right-on-click>Click Me</div>

如果它在您的 include 的 html 中,jquery 内容将通过指令自动连接。

关于jquery - Angular : ng:include for current template and scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13004158/

相关文章:

javascript - 动态添加 <form :input> textbox in jsp

angularjs - ADAL JS Angular-WebAPI 向 token 添加新的角色声明

javascript - AngularJS 不会在 img 选项卡内渲染范围

jquery - IE7 Jquery 位置 : Relative

javascript - 添加在。 ('click' ) 函数用于新创建的按钮,单击之前触发事件

javascript - AngularJS 数据绑定(bind) - 观察周期未触发

javascript - Jasmine Controller 测试,预计 spy 已被调用

javascript - Angular JS - 如果使用 HTML 元素成功提交表单,则通知用户

javascript - 触发表单操作

javascript - 如何在 Adob​​e Muse 中将 iframe 滚动到顶部?