将 javascript 变量传递到 angularJS 作用域

Passing a javascript variable into a angularJS scope

本文关键字:angularJS 作用域 javascript 变量      更新时间:2023-09-26

所以我正在使用MEAN堆栈创建一个网页,并保存了用户变量,以便使用sessionStorage的HTML5/Javascript变量在每个页面上携带。

我们现在尝试通过控制器将此值传递给 angularJS。但是,问题是,我们不知道如何在不让用户键入值的情况下将其传递到提交文件中。我们尝试将用户名显示为只读并使用getElementByID设置值,但是angularJS无法识别新值,而是从旧字段中获取值,该值为",因为文本字段的值一开始是空白的,因此用户在angularJS范围内未定义。

我们还尝试将该值作为隐藏范围传递,这也不起作用,因为角度

有没有办法只在ng模型中声明变量?问题是任何ng值都使用",所以它总是认为该值只是"user"只是文本"user",而不是实际上的变量。

任何帮助将不胜感激

如果您已将用户名保存到会话存储中,如下所示:

window.sessionStorage.setItem("username","toby");

然后在角度控制器中,您可以:

$scope.username = window.sessionStorage.getItem("username");(编辑:这不会将username绑定到会话存储(

注意:如果要将JSON存储在会话/本地存储中,则应事先将其设置为JSON:

window.sessionStorage.setItem("userObject", JSON.stringify(userObject));

并检索:

var userObject = JSON.parse(window.sessionStorage.getItem("userObject"));

如果要监视会话存储,可以使用$watch

$scope.$watch(
    function(){return window.sessionStorage.getItem("username");},
    function(newVal, oldVal){
        console.log("Username changed from", oldVal, "to", newVal);
    }
);

您可能需要使用 angularJS $apply(( 函数才能获得角度以响应更新的值。查看这篇关于 $apply(( 的有用文章。当您对 Angular 不知道的模型进行更改时,您需要调用 $apply((,例如,在$http调用之外,Angular 将自动对其进行 $apply(( 调用(。您应该将函数包装在 $apply(( 调用中,即

$scope.$apply(function(var) {
    etc.
}

此外,若要将控制器中的值放入模型中(假设使用的是 MVC 框架(,需要在控制器中声明一个模型变量。例如,您可能有一个控制器,该控制器开始:

.controller("exampleCtrl", function($scope) {
    $scope.model = model;
}

然后,您可以通过调用来创建/更新模型中的值

$scope.model.VALUENAME = whatever value

希望这有帮助!

这对

我有用:

// in the javascript only section call an angular method to update the data when OnClick, OnChange, etc....
angular.element(document.getElementById('YourElementId')).scope().update_your_value(); 

//inside the angular controller
$scope.update_your_value =  function(){
    $scope.your_model.value        = $('#YourElementId').val(); //  or document.getElementById('YourElementId')).value
    $scope.$apply();
}