我是angularJS的新手,我试图让简单的事情发挥作用,但我失败了。
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>
<script src="main.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="main.css">
</head>
<body ng-app="app" ng-strict-di>
<div class="test" ng-controller="testSrc">
<p> {{ blah }} </p>
<img ng-src="{{ URLImage }}"/>
<button class="btn btn-sucess" ng-click="goYahoo()">Yahoo</button>
<button class="btn btn-sucess" ng-click="goGoogle()">Google</button>
</div>
</body>
</html>
JS:
var app = angular.module("app", []);
app.controller('testSrc', ['$scope,$location', function ($scope, $location) {
"use strict";
$scope.blah = "blah blah";
$scope.URLImage = 'https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png';
$scope.goGoogle = function () { $location.url('localhost:58164/g'); };
$scope.goYahoo = function () { $location.url('localhost:58164/y'); };
}]);
app.config(function ($routeProvider) {
"use strict";
$routeProvider
.when('/', {
templateUrl : 'index.html'
})
.when('/g', {
templateUrl : 'http://www.google.com'
})
.when('/y', {
templateUrl : 'http://www.yahoo.com'
});
});
代码已通过所有lint警告。我使用括号的实时预览打开Internet Explorer。我遇到了3个问题:
1){{blah}}并没有转化为等等,我看到{{blah}}好像忽略了js。对于img的ng-src也是如此。它被忽略了,我看不到图像。
2)2个按钮没有涂成绿色,因为我希望它来自bootstrap css。我在jsFiddle中尝试了它并确实看到它们是绿色但是当我现在再次尝试时,它们是常规的,不知道我做错了什么。
3)路由:我想使用2个按钮导航到特定的URL和y时浏览到Google / Yahoo。当我打开实时预览时,网址为:http://127.0.0.1:58164/index.html,那么如何才能正确路由? http://127.0.0.1:58164/index.html/g无法工作。
我有点迷失在这里,不确定问题是否是我的代码,现场预览的浏览器虽然JS也没有在jsFiddle工作......
答案 0 :(得分:2)
1)您错误地将依赖项注入控制器 - 您需要为函数的每个参数添加一个字符串。这是一个容易犯的错误!
app.controller('testSrc', ['$scope,$location', function ($scope, $location) { // Wrong
app.controller('testSrc', ['$scope', '$location', function ($scope, $location) { // Right
2)您在按钮中拼错了班级名称。 &#39; sucess&#39;应该是成功&#39;
<button class="btn btn-sucess" ng-click="goYahoo()">Yahoo</button>
^^^^^^
3)你的路由有很多问题:
var app = angular.module("app", ["ngRoute"]);
并在HTML中添加ng-view
标记。所有这一切,我都不认为ngRoute会帮助你完成你想要做的事情。路由器设计用于路由应用程序的页面,而不是外部站点,因此尝试从其他域加载HTML可能无法正常工作。
如果您还没有通过official Angular tutorial,我建议您使用它 - 它很好地涵盖了所有这些内容。我还推荐Shaping Up With Angular.js on Code School,如果你更喜欢动手的话。