作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 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/
我是一名优秀的程序员,十分优秀!