Как получить доступ к переменной, объявленной в контроллере из представления?

0

Я новичок в AngularJS. Мне трудно понять, как обращаться к переменным, указанным в контроллере, из представления. Например, в приведенном ниже коде я не могу получить доступ к переменной filePath

HTML

<div ng-controller = "buttonViewCtrl as buttonCtrl">
      {{ buttonCtrl.filePath }}
</div>

JS

.controller('buttonViewCtrl', ['$scope', '$location', function($scope, $location) {
    $scope.filePath =  '';
    $scope.nav = function() {
        $scope.filePath = "Logged In";
 };

Я предоставляю все свое приложение ниже для контекста:

index.html:

<!DOCTYPE html>
<html lang="en" ng-app="myApp" class="no-js"> 
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>My AngularJS App</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/normalize.css">
    <link rel="stylesheet" href="bower_components/html5-boilerplate/dist/css/main.css">

    <link rel="stylesheet" href="app.css">

    <script src="bower_components/html5-boilerplate/dist/js/vendor/modernizr-2.8.3.min.js"></script>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"/>
    <link rel="shortcut icon" href="images/favicon.ico" />
    <link rel="stylesheet" href="css/anchour/anchour.css"/>
  </head>

  <body>
    <div ng-view></div>
    <div>Angular seed app: v<span app-version></span></div>

    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="app.js"></script>
    <script src="view1/view1.js"></script>
    <script src="view2/view2.js"></script>
    <script src="buttonView/buttonView.js"></script>
    <script src="components/version/version.js"></script>
    <script src="components/version/version-directive.js"></script>
    <script src="components/version/interpolate-filter.js"></script>
  </body>
</html>

app.js:

'use strict';

 angular.module('myApp', [
  'ngRoute',
  'myApp.view1',
  'myApp.view2',
  'myApp.version'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/view1'});
}]);

view1.html:

<div class="squirrel"> 
      <div class="logo"></div>
      <cite>Every brand has a story.</cite>
      <h2> <a>Watch the video </a></h2>
      <aside> &#x2192; </aside>

      <button type="button" class="btn btn-default btn-lg navButton" aria-label="Center Align" ng-controller = "buttonViewCtrl" ng-click="go('/buttonView')">
        <span class="glyphicon glyphicon-align-justify" aria-hidden="true"></span>
      </button>

      <div id = "arrow">
        <img src = "images/pointer.png" alt = "arrow">
      </div>
    </div>

    <div class = "panda">
      <button type="button" class="btn btn-default btn-lg work"> SEE OUR WORK </button>
    </div>

    <div class = "experience">
      <h1> Our team builds great brands and experiences. </h1>
      <button type="button" class="btn btn-default btn-lg team"> MEET THE TEAM </button>
    </div>

    <section class = "about">
      <h5> WHAT ARE WE? </h5>
      <h2> Anchour is a branding agency based in Maine. </h3>

      <p> We weave together creative solutions to build personal brands and experiences. We work closely with your brand to understand your needs and create solutions that produce real results. By integrating the power of identity, digital, and sensory design, we bring new life to brands everywhere.
      </p>
    </section>

    <div class = "goodWork">
      <div class = "spotlight"> 
        <h3> <a href = "#"> Spotlight: Amanda Brill of Las Vegas </a> </h3>
        <p> Amanda Brill is a Designer at Anchour. Fueled by the purpose of helping others, she works to bring the identity of a brand to life through a creative and intensive design process. to help brands effectively communicate who they she works to bring the identity of a brand to life through a creative... </p>
        <footer> <a href = "#"> Read More </a> </footer>
      </div>

      <div class = "spotlight"> 
        <h3> <a href = "#"> Spotlight: Amanda Brill of California </a> </h3>
        <p> Amanda Brill is a Designer at Anchour. Fueled by the purpose of helping others, she works to bring the identity of a brand to life through a creative and intensive design process. Her goal is to use design as a way to help brands effectively communicate who they sponsor and supporter Fueled by the purpose of.. </p>
        <footer> <a href = "#"> Read More </a> </footer>
      </div>

      <div class = "spotlight"> 
        <h3> <a href = "#"> Varney Agency: Protecting What You </a> </h3>
        <p> Anchour produced Varney Agencys latest spot featuring Matt Albrecht, owner of River Drive. Working with companies from all around the world, River Drive buys, sells, reconditions and recycles reconditions and ecycles owner of used. River Drive buys, sells Varney Agencys latest spot featuring Matt Albrecht.</p>
        <footer> <a href = "#"> Read More </a> </footer>
      </div>

      <div class = "spotlight"> 
        <h3> <a href = "#">Announcing support of Not Here </a> </h3>
        <p> This week is Human Trafficking Awareness Week, so its great timing to share how proud we are to be a sponsor and supporter of Not Here latest spot featuring Matt Albrecht, reconditions and recycles owner of River Drive. Working with companies from all around the,a River Drive buys, sells.... </p>
        <footer> <a href = "#"> Read More </a> </footer>
      </div>
    </div>

    <div class = "start">
      <h2 id = "startWork"> Want to work with us? </h2>
      <button type="button" class="btn btn-default btn-lg"> Get Started &#x2192; </button>
    </div>

    <div id = "end">
      <footer>
        <a href = "#"> Home </a>
        <a href = "#"> About us </a>
        <a href = "#"> Our Team </a>
        <a href = "#"> Blog </a>
        <a href = "#"> Services </a>
        <a href = "#"> Portfolio </a>
        <a href = "#"> Contact </a>
        <a href = "#"> Sitemap </a>
    </footer>
    </div>

view1.js:

'use strict';

angular.module('myApp.view1', ['ngRoute'])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.
            when('/view1', {
                templateUrl: 'view1/view1.html',
                controller: 'View1Ctrl'
        }).
            when('/buttonView', {
                templateUrl: 'buttonView/buttonView.html',
                controller: 'buttonViewCtrl'
        });
    }])

.controller('View1Ctrl', [ '$scope', function($scope) {
    $scope.name = '';
    $scope.names = [{name:"Chris"}, {name:"Calvin"}];
    $scope.addName = function() {
    $scope.names.push( {'name':$scope.name} );
    $scope.name = '';
    };
    }])

.controller('buttonViewCtrl', ['$scope', '$location', function($scope, $location) {
    $scope.go = function( path ) {
        $location.path( path );
 };
}]);    

view2.html

<p> What is going on </p>

view2.js:

'use strict';

angular.module('myApp.view2', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view2', {
    templateUrl: 'view2/view2.html',
    controller: 'View2Ctrl'
  });
}])

.controller('View2Ctrl', [function() {

}]);

buttonView.html

<a href = "#"> Home </a> 
<a href = "#"> About us </a> 
<a href = "#"> Why </a>

buttonView.js

'use strict';

angular.module('myApp.buttonView', ['ngRoute'])
    .config(['$routeProvider', function($routeProvider) {
        $routeProvider.when('/buttonView', {
            templateUrl: 'buttonView/buttonView.html'
        });
    }])
Теги:

2 ответа

0
Лучший ответ

Когда вы используете $ scope для заданных данных, вы можете использовать его напрямую

angular
  .module('app')
  .controller('buttonViewCtrl', ['$scope', '$location', function($scope, $location) {
    $scope.filePath =  '';
    $scope.nav = function() {
        $scope.filePath = "Logged In";
 };
<div ng-controller = "buttonViewCtrl">
      {{ filePath }}
</div>

Если вы хотите использовать синтаксис controllerAs (лучший способ), он должен выглядеть так:

angular
  .module('app')
  .controller('buttonViewCtrl', ['$scope', '$location', function($scope, $location) {
    var mv = this;
    
    mv.filePath =  '';
    mv.nav = function() {
        mv.filePath = "Logged In";
 };
<div ng-controller = "buttonViewCtrl as buttonCtrl">
      {{ buttonCtrl.filePath }}
</div>
  • 0
    Спасибо, что было полезно. Вы знаете, почему это так?
  • 0
    $ scope мы используем из первой версии (это была основная идея angular), но со временем развивается понимание всех пробелов (например, никоим образом, если вы хотите вызывать метод parent foo а в текущей области видимости есть метод с тем же именем) и angular team add способность связывать this контроллер.
0

ваше представление настроено для псевдонимов контроллера, но ваш контроллер настроен для $ scope way

поэтому, чтобы сохранить представление с помощью псевдонима контроллера, вам нужно изменить свой контроллер, чтобы использовать эту структуру вместо текущей

this.filePath = "Logged In";

но если вы хотите выполнить кепп-путь, тогда нет необходимости в псевдониме контроллера в представлении, измените его на это

<div ng-controller = "buttonViewCtrl">
  {{filePath}}
</div>

обратите внимание, что мы напрямую обращаемся к переменной $ scope без какого-либо доступа (например, псевдонима контроллера)

Ещё вопросы

Сообщество Overcoder
Наверх
Меню