我正在倾向 Angular 的路线。只需设置 template 属性即可非常清楚如何将 View 加载到 ng-view 中。
假设我在 View 上有一个小部件。当用户导航到/#/changeWidget 时,如何仅替换小部件内容?
在我看来,我只能使用单个ng-view
main.html
<div ng-app="payment">
<div ng-view></div>
</div>
js
var app = angular.module("payment",["ngRoute"]);
function listController($scope) {
}
app.config(function($routeProvider, $locationProvider){
$routeProvider.when('/list', {
templateUrl: 'templates/list.html',
controller: listController
}).
when('/chagneWidget', {
templateUrl: 'templates/widget2.html',
controller: widget2Controller
}).
otherwise({
redirectTo: '/list'
});
});
所以基本上,当'/changeWidget'被触发时,我只想替换list.html中的一个div
是否可以使用路由器或者我应该做... ajax 调用并操作 DOM?
最佳答案
我认为使用 Angular router
不可能轻易实现这一点——说实话,这是它的一个很大的限制。但是,嘿,有一个非常漂亮且流行的模块提供了这种可能性:ui-router 。如果您不阅读文档:
Warning: UI-Router is pre-beta and under active development. As such, while this library is well-tested, the API is subject to change. Using it in a project that requires guaranteed stability is not recommended.
真的有必要通过改变路线来更新小部件吗?如果没有,有很多选择可以以 Angular 来实现。如果你确实需要改变路线,你可以使用这个技巧:
$scope.$on("$locationChangeStart", function (event, next, current) {
if (next == 'your_domanin/your_specific_url') {
setTimeout(function() {
$window.history.pushState("object or string",
"Title", '/your_specific_url')},20);
event.preventDefault();
// ... update your view
}
});
关于angularjs - 如何替换ng-view中的部分节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20253162/