gpt4 book ai didi

javascript - 如何将值从 Controller 外部传递到作用域?

转载 作者:行者123 更新时间:2023-11-28 01:31:11 25 4
gpt4 key购买 nike

我是 Angular 世界的新手,我有一个功能,可以在加载时加载特定 div 内的 html,然后 Controller 进行初始化。我想让单个变量在 Controller 内部可用,所以想知道是否可以从 Controller 外部将该变量分配给范围。

//controller 
var cntlrs = angular.module('MyModule');

cntlrs.controller('ControllerTest', function ($scope, $http) {
//want to have var available here from $scope
});


//accessing scope from outside
var appElmt = document.querySelector('[ng-app=MyApp]');
var $scope = angular.element(appElmt).scope();
var customer = "New Customer";

//how can I set customer value inside scope?

最佳答案

我建议更多地阅读 Angular 文档。 $scope 是您的模型(或者术语 ViewModel 可能更合适)。

为了将值输入 Controller ,我会推荐一家工厂或服务。可以在工厂上调用 setCustomer,然后其他 Controller 将能够使用 getCustomer 查看该值。

var mod = angular.module('MyModule', []);

mod.factory("CustomerFactory", function () {
var customer;
return {
getCustomer: function () {
return custData;
}
setCustomer: function (custData) {
customer = custData;
}
}
});

mod.controller("TestController", function ($scope, $http, CustomerFactory) {
$scope.customer = CustomerFactory.getCustomer();
}

如果您没有在 Angular 之外引用 $scope(即来自 angular.element(...).scope()),这也可能会更好。我不知道你想解决什么问题,但从上面的代码看来,所有逻辑都可以放在 Controller 内。

关于javascript - 如何将值从 Controller 外部传递到作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22105480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com