2014-11-21 60 views
0

我想訪問javascript變量,然後在控制器中更改它,然後在路由中使用它..但它顯示的是同一個舊的。在angularjs中訪問javascript變量

var userEditid = 0; 

app.controller("cn_newuser", function ($scope,$window) { 
    editUser = function (this_) { 
     $window.userEditid = this_.firstElementChild.value; 
     alert(userEditid); 
     //window.location.path("#/edit_user"); 
     //$window.location.href = "#/edit_user"; 
    } 

中的Abobe路線userEditid路線

.when("/edit_user", { 
    templateUrl: "/master/edituser/" + userEditid //userEditid should be 3 or some thing else but is showing 0 
}) 

應該是3或者一些別的東西,但正顯示出0

回答

0

這是因爲.when()是在應用實例,當這個全局變量進行評估(這實際上並不是一個好主意)設置爲0,而不是控制器運行時。如果你試圖說,「加載模板,但模板名稱應該根據特定變量而變化」,那麼你正在做的方式是行不通的。

我會做兩兩件事在這裏:

  1. 保存在服務您的變量,所以你不要有全局變量玩
  2. 有一個主模板,它使用了NG-包括,其中有通過VAR

變量在服務確定的模板:

app.controller("cn_newuser", function ($scope,UserIdService) { 
    $scope.editUser = function (this_) { 
     UserIdService.userEditid = this_.firstElementChild.value; 
     $location.path('/edit_user'); 
    } 
}); 

阿爾斯Ø注意,我改變了它使用$location.path()

主模板:

.when("/edit_user", { 
    templateUrl: "/master/edituser.html", controller: 'EditUser' 
}); 

EditUser控制器:

app.controller("EditUser", function ($scope,UserIdService) { 
     $scope.userTemplate = '/master/edituser/'+UserIdService.userEditId; 
    }); 

然後edituser.html是:

<div ng-include="userTemplate"></div> 

當然,我會問爲什麼你會想要一個單獨的模板每個用戶,而不是一個單一的模板由Angular動態修改,但這不是你問的。

編輯:

服務會像

app.factory('UserIdService',function() { 
    return { 
    userEditId: null 
    } 
}); 

至於這麼簡單。

+0

謝謝...我是新來的角...你可以告訴我什麼是服務代碼\ – user2601893 2014-11-21 06:20:23

+0

是的,你有一個小提琴的地方? – deitch 2014-11-21 06:36:06

+0

不要太難過;角度是神話般的,但學習曲線陡峭,教程是可怕的。但越來越多,每天上網。 – deitch 2014-11-21 06:39:22