我有一些提示:首先,您的库不应该包含在视图中。您应该只在应用程序的一个点中包含该库。可以是异步的(通过 JavaScript),或者通过在索引文件中为库添加 script 标记。
如果您决定通过 JavaScript 添加库,请考虑进行检查以防止多次包含,例如,
if (!window.jQuery) {
//include jQuery library
}
您也可以在 index/main html 文件中添加 script 标签,如果您想异步加载它,可以添加属性 async或 defer。
-- 看看 HTML 5 <script> Tag。
现在,与 AngularJS 相关,当您加载部分视图时,会引发事件 $includeContentLoaded,每次 ngInclude 内容已重新加载。
如果您包含两个或更多部分视图,您应该询问要加载库/插件或进行一些 DOM 操作的特定视图,例如,
controller.js
angular
.module('myApp')
.controller('HomeCtrl', [
'$scope', '$window',
function ($scope, $window) {
'use strict';
var homeCtrl = this,
$ = jQuery; //safe alias
//Emitted every time the ngInclude content is reloaded.
$scope.$on('$includeContentLoaded', function (event, source) {
if ('src/pages/home/zipcodeForm/view.html' === source) {
//initialize your jQuery plugins, or manipulate the DOM for this view
}
else if('src/pages/home/section1/view.html' === source){
//initialize your jQuery plugins, or manipulate the DOM for this view
}
});
//Can be used to clean up DOM bindings before an element is removed
//from the DOM, in order to prevent memory leaks
$scope.$on('$destroy', function onDestroy() {
//destroy event handlers
});
}
]);
这里重要的代码是事件$includeContentLoaded。访问网站了解更多信息:https://docs.angularjs.org/api/ng/directive/ngInclude
如果你使用ng-view应该没有问题,在路由器中注册视图即可(有很多方法可以实现)
module.js
angular
.module('myApp', ['ngRoute' /*, other dependecies*/]);
router.js
angular
.module('myApp')
.config(['$routeProvider', '$locationProvider',
function ($routeProvider, $locationProvider) {
'use strict';
$routeProvider
.when('/', {
templateUrl: 'src/pages/home/view.html',
controller: 'HomeCtrl',
controllerAs: 'homeCtrl',
reloadOnSearch: false
})
.when('/index.html', {
redirectTo: '/'
})
.when('/home', {
redirectTo: '/'
})
.when('/404', {
templateUrl: 'src/pages/error404/view.html',
controller: 'Error404Ctrl',
controllerAs: 'error404Ctrl'
})
.otherwise({
redirectTo: '/404'
});
/*
Set up the location to use regular paths instead of hashbangs,
to take advantage of the history API
$locationProvider.html5Mode(true);
*/
}
]);
当视图被加载时,它会发出事件:$viewContentLoaded 表示 DOM 已加载,然后您可以安全地初始化 jQuery 插件。
controller.js
angular
.module('myApp')
.controller('HomeCtrl', [
'$scope', '$window',
function HomeCtrl ($scope, $window) {
'use strict';
var homeCtrl = this, //the controller
$ = jQuery; //safe alias to jQuery
//Emitted every time the ngView content is reloaded.
$scope.$on('$viewContentLoaded', function() {
$('.slickSlider').slick({
slidesToShow: 4,
arrows: true,
slidesToScroll: 1
});
});
}
]);
重要提示:在前面的代码中,包含脚本的顺序很重要。
- module.js
- router.js
- controller.js
我强烈推荐使用自动化工具,例如 gulp