更改URL而不重新加载Angularjs中的控制器

时间:2015-05-22 18:02:49

标签: angularjs

最初,我在表格中显示所有用户名。一旦用户选择了任何一个名称,我就以所选用户作为参数调用LoadData方法。我正在更改URL#/ Trades / User / User1并在User1下附加详细信息。我的要求是1)在LoadData方法中,我想根据选择将URL更改为#/ Trades / User / User1或#/ Trades / User / User2 2)它应该更新数据并反映在视图中,但是它不应该重新加载控制器。

HTML

<div ng-app="myApp" ng-controller="myCtrl"> 
<table>
    <tr ng-repeat-start="val in data.Titles" class="h" ng-click="LoadData(val.title)">
        <td colspan="2" ng-hide="val.title == undefined">{{val.title}}</td>
    </tr>
    <tr ng-repeat="con in val.details">
        <td>{{con.portfolio}}</td>
        <td>{{con.status}}</td>
    </tr>
    <tr ng-repeat-end>
        <td colspan="2">Load More</td>
    </tr>
 </table>
</div>

代码

angular.module("myApp", [])
    .controller("myCtrl", ["$scope", function ($scope) {

        $scope.data = {"Titles":[{title:"User 1",    
            details: [{portfolio: "Microsoft", status:"Active"},{portfolio:"IBM", status:"Inactive"}]
    }, {title:"User 2",
        details: [{portfolio: "Yahoo", status:"Inactive"},{portfolio: "Google", status:"Active"}]
    }]};

$scope.LoadData = function(id) {
    Change the url as #/Trades/Author/User1
    Load the details of the User1
};
    });

1 个答案:

答案 0 :(得分:1)

你可以试试这个。我目前在我的项目中使用这个非常相似的东西。 http://joelsaupe.com/programming/angularjs-change-path-without-reloading/

app.run(['$route', '$rootScope', '$location', function ($route, $rootScope, $location) {
    var original = $location.path;
    $location.path = function (path, reload) {
        if (reload === false) {
            var lastRoute = $route.current;
            var un = $rootScope.$on('$locationChangeSuccess', function () {
                $route.current = lastRoute;
                un();
            });
        }
        return original.apply($location, [path]);
    };
}])