2012-10-22 63 views
2

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

的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?

+0

你能告诉你的代码,它定义了'NG-include'指令范围'$ service'? – Tosh

+0

嗯......也许这就是我想念的东西?我没有在任何地方定义$ service。你能举一个我怎么做的例子吗? – corinnaerin

+0

我设法让它与一些迂回解决方案一起工作:http://jsfiddle.net/xSyZX/11/。但是,我并没有意识到在部分评估之前onload会执行,所以它仍然不会按照我的意愿去做。我曾经和我一起工作过的人谈过,他建议把它封装到一个jQuery插件中,并使用angularui的jQuery Passthrough或者为它创建一个自定义指令。 – corinnaerin

回答

2

如果你想使用jQuery在页面上影响元素时就将加载/处理,在“角办法”做这将是创建一个没有jQuery的为你工作的自定义指令。控制器不应该在执行DOM操作,并且加载功能实际上是针对包含的“业务”逻辑而设置的。

这里,一旦它处理应用一些JQuery的一些元素的指令的一个例子:

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> 

如果这是你包括的HTML,jQuery的东西会得到自动指令接线。