2012-10-22 64 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的東西會得到自動指令接線。