简体   繁体   English

Angularjs。 获取控制器的范围。 未知的提供程序错误

[英]Angularjs. Get scope of controller. Unknown provider error

On index.html page I have following controller declaration: 在index.html页面上,我具有以下控制器声明:

<div ng-controller="UserDataController"/>

I need this declaration because somewhere in my templates I have following code (I know it is a bad style, but ...): 我需要此声明,因为在模板的某处有以下代码(我知道这是一种不好的样式,但是...):

<script>

    var userData = angular.element('[ng-controller=UserDataController]').scope().userData;
...
 </script>

But at the same time I'm working with resources(REST) and have code similiar to this one . 但在同一时间,我用资源(REST)的工作,并有代码类同这一个 Which throws in my case error: Unknown provider: dataProvider <- data, because my controller looks like: 在我的情况下抛出错误:未知提供程序:dataProvider <-数据,因为我的控制器如下所示:

function UserDataController($scope,data)
{
    $scope.userData = data;
}

I've read here that this is because of ng-controller declaration. 我在这里读到这是因为ng-controller声明。 And of course when I removed this declaration the part of code between script tags in my templates is broken. 当然,当我删除此声明时,模板中脚本标记之间的代码部分已损坏。 So, I'm in controversial situation -- when I repair one thing, another get broken... 所以,我处于有争议的情况-当我修理一件东西时,另一件就坏了...

I'm not strong in js and jquery, but the easiest way seems to me is to get somehow controller scope without this selector '[ng-controller=UserDataController]'. 我不擅长js和jquery,但对我来说,最简单的方法似乎是在不使用此选择器'[ng-controller = UserDataController]'的情况下获得控制器范围。 How can it be done? 如何做呢? Is it a right approach? 这是正确的方法吗?

Thanks in advance! 提前致谢!

I think you're trying to access your userData object all wrong. 我认为您正在尝试完全错误地访问userData对象。 To access the userData object, simply do a {{userData}} somewhere on your page that is within the scope of your controller. 要访问userData对象,只需在页面上位于控制器范围内的某个地方执行{{userData}} For instance 例如

<div ng-app>
    <div ng-controller="UserDataController">
        <input type="text" ng-model="userData" />
        <div ng-model="userData">User data is: {{userData}}</div>
    </div>
</div>

and then your JS 然后你的JS

function UserDataController($scope)
{
    $scope.userData = '';
}

check this fiddle: http://jsfiddle.net/N4MQ4/2/ 检查此小提琴: http : //jsfiddle.net/N4MQ4/2/

the error: 错误:

Unknown provider: dataProvider <- data.... 

implies that you're trying to use angular's dependency injection to inject the data param for you. 表示您正在尝试使用angular的依赖项注入为您注入数据参数。 From the error, I'm guessing there is no provider configured for data. 从错误中,我猜测没有为数据配置提供程序。 Hence, the error you're seeing. 因此,您看到的错误。 like ronnie, it does seems a bit strange as to why you're doing it the way you are doing 像ronnie一样,为什么这样做的方式确实有点奇怪

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM