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

$scope var not placing data inside index file

本文关键字:文件 置数据 索引 scope var      更新时间:2023-09-26

谁能告诉我为什么我的代码将不放置'controller is working'在

{{jsVariable}} ? ?我都快疯了。

HTML代码:

<!-- 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 = ng-controller"myApp"="控制器">

<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';
    }
}]);

在控制台中,我确实得到了一个成功的'bob: controller is working'

更新:

我让它更简单:索引文件:

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

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

. .div ng-app="myApp" ng-controller="myCtrl">

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

. .div>

app.js文件:

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

controller.js文件:

app.controller('myCtrl', ['$scope',function($scope) {
    $scope.jsVariable = 'controller is working';

}]);

我想你可能没有设置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';
}

}]);

您刚刚创建了Function $作用域。鲍勃,但你从来没打过。只需用$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>