简体   繁体   中英

value wont pass to controller from provider angularjs

So I have a controller and a provider which I am trying to pass a value from the provider to the controller, nothing too complex. I have been through several tuts and forum threads about this but non eof the e=suggestions are working. Worst off I am not getting any errors in my console either, just a blank page. I am sure that this is something stupid small Im missing but I am stumped.

   var app = angular.module('myApp', ['ngRoute']);

   app.controller('SettingsCtrl', function($scope, Stocks) {
        $scope.stock = Stocks;
   });

app.provider('Stocks', function() {
    this.name = 'some name';
    this.$get = function() {
        this.name = 'Ford Motors'
        return this.name;
    };
});

app.config(function($routeProvider) {
$routeProvider
    .when('/settings', {
        templateUrl: 'templates/settings.html',
        controller: 'SettingsCtrl'
    })
    .otherwise({redirectTo: '/'});
  });

HTML

<!doctype html>
<html data-ng-app="myApp" data-ng-csp="">
    <head>
        <meta charset="UTF-8">
        <title>Presently</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>
        <div ng-view></div>
        <script src="js/angular.js"></script>
        <script src="js/angular-route.js"></script>
        <script src="js/app.js"></script>
    </body>
</html>

settings.html

<div class="container">
     <div class="stock_name">{{stock.name}}</div>
</div>

You should use ngView :

<body>
  <div ng-view></div>

And put the content inside the template:

<!-- templates/settings.html' -->

<div class="container">
  <div class="stock_name">{{stock.name}}</div>
</div>

Also redirect to you route:

.otherwise({redirectTo: '/settings'});

Look at your Stocks provider

app.provider('Stocks', function() {
    this.name = 'some name';
    this.$get = function() {
        this.name = 'Ford Motors'
        return this; //<-----instead of 'this.name'
    };
});

Because this.name always return name not Stocks object . Now your expression {{stock.name}} will evaluate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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