How to replace a part of sections in ng-view?

时光总嘲笑我的痴心妄想 提交于 2019-12-11 02:49:59

问题


I'm leaning Angular's route. It's very clear how to load a view into ng-view by simply setting template attribute.

Let's say I have a widget on a view. When a user navigate to /#/changeWidget, how do I replace ONLY the widget content?

it looks like to me that I can only use single 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'
        });

    });

So basically, when '/changeWidget' gets triggered, I just want to replace a div from list.html

is it possible with router or should I just do...an ajax call and manipulate DOM?


回答1:


I do not think it is easily possible with angular router -- and to be honest is quite a big limitation of it. But hey there is this very nice and popular module which offers such possibility: ui-router. In case you do not read documentation:

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.

Is it really necessary to update the widget by changing the route? If not there are plenty of options to do it in angular. If you really have to change the route you can use this hack:

$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
    }
});



回答2:


What would be wrong with using ngSwtich?

The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression... The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element matches the value obtained from the evaluated expression.

http://docs.angularjs.org/api/ng.directive:ngSwitch



来源:https://stackoverflow.com/questions/20253162/how-to-replace-a-part-of-sections-in-ng-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!