$ scope var不将数据放在索引文件中

时间:2016-11-04 23:08:58

标签: javascript angularjs express

任何人都可以告诉我为什么我的代码不会放置'控制器正在工作'在里面

{{jsVariable}} ??我不知道这件事。

HTML code:

<!-- AngularJS -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script> 

<script src="/js/app.js"></script>
<script src="/js/controller.js"></script>

 

... ng-app =&#34; myApp&#34; NG-控制器=&#34;控制器&#34;&GT;

<h1>asd {{jsVariable}} asd</h1>

控制器代码:

    app.controller('controller', ['$scope',function($scope) {

    $scope.jsVariable = 'controller is working';
    $scope.bob = function() { 
        console.log("bob: " + $scope.jsVariable);
        $scope.jsVariable = 'controller is working';

    }

}]);

在控制台中我确实得到了一个很好的东西:控制器正在运行&#39;

更新:

我会让它变得更简单: 索引文件:

<script src="/js/app.js"></script>
<script src="/js/controller.js"></script>

// body(出于某种原因,stackoverflow不允许我放置body,div和head标签,但在我的代码中确实存在)

.. div ng-app =&#34; myApp&#34; NG-控制器=&#34; myCtrl&#34;&GT;

<h1>asd {{jsVariable}} asd</h1>

.. DIV&GT;

app.js文件:

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

controller.js文件:

app.controller('myCtrl', ['$scope',function($scope) {

    $scope.jsVariable = 'controller is working';



}]);

2 个答案:

答案 0 :(得分:0)

我认为您可能没有设置ng-app和/或ng-controller。我有一个代码版本显示在这里:

HTML

  <html data-ng-app="app"><!-- I set up ng-app here -->
  <head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script> 

<script src="controller.js"></script>

</head>
<body>
<div data-ng-controller="controller"> <!--I set the ng-controller here -->
<h1>asd {{jsVariable}} asd</h1>
</div>
</body>

我认为我没有改变angularjs,但以防万一:

 let app = angular.module('app', []);

 app.controller('controller', ['$scope',function($scope) {

$scope.jsVariable = 'controller is working';
$scope.bob = function() { 
    console.log("bob: " + $scope.jsVariable);
    $scope.jsVariable = 'controller is working';

}


}]);

答案 1 :(得分:0)

您只需创建Function $ scope.bob,但您永远不会调用它。 只需使用$ scope.bob();

添加一个新行

像这样的东西

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
</head>
<body ng-app="myApp" ng-controller="MyController">
    <div>
    Anything you want
</div>
<script>

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

    myAppModule.controller('MyController', ['$scope', function ($scope) {

        $scope.jsVariable = 'controller is working';

        $scope.bob= function () {
            console.log("bob: " + $scope.jsVariable);
            $scope.jsVariable = 'controller is working';
        };

        $scope.bob();
    }]);

</script>
</body>
</html>