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

标签 javascript angularjs function angularjs-scope angular-ui

我是 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/

相关文章:

javascript - 将 facebook 分享按钮链接到 FB.ui()

javascript - 将 ng-model 值动态设置为 AngularJS 中 js 变量的值

javascript - 我如何在 angularjs promise 中解析这个结果

angularjs - Socket.io socket.broadcast.to 不工作

sql - 如何在 SQL 中创建带有 2 个参数的函数?

c - 函数中的空指针

javascript - Angular JS Controller 没有响应

javascript - 进行 oauth 时如何创建弹出窗口?

javascript - 页面重定向在 Angular JS 中不起作用

c++ - 遍历链表C++并返回用户输入的最高值