Angular:ng:包含当前模板和范围?

时间:2012-10-22 02:03:47

标签: jquery angularjs

我是Angular的新手,但我已经搜索了好几个小时,似乎无法弄清楚我做错了什么......我想解决的问题是能够执行一些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>

residential.html

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

controllers.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?

1 个答案:

答案 0 :(得分:2)

如果你想在页面上加载/处理元素时使用JQuery来实现元素,那就是&#34;角度方式&#34;这样做是为了创建一个让jQuery为你工作的自定义指令。控制器不应该进行DOM操作,并且onload功能实际上适用于&#34; business&#34;为此设置的逻辑包括。

以下是一个指令的示例,该指令在处理完一些元素后立即应用它:

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的东西将被指令自动连接。

相关问题