控制器中的功能未被击中

时间:2015-11-25 19:55:53

标签: javascript angularjs html5 angularjs-controller

第一次询问aq,所以如果我做错了,请告诉我,以便我可以解决它,因为我已经尝试在这里找到答案,但不能,所以任何和所有的帮助将不胜感激。

我正在尝试使用控制器加载一个“国家/地区”列表,一切似乎进展顺利,没有错误,没有警告,它加载模块并点击角度控制器,但它从未达到功能/去进入控制器功能内部的代码。我错过了什么吗?我做错了吗?

Register.cshtml

<div ng-app="RegisterApp" class="form-group" ng-controller="CountriesController as CountriesCtrl">
    <label class="input-desc">Country</label>
    <select ng-model="country" 
      ng-options="country.Id as country.Name for country in countries">
        <option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
    </select>
</div><!-- End .from-group -->

RegisterApp.js

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

CountriesService.js

/// <reference path="../App.js" />

angular.module("RegisterApp").service("CountriesService", function ($http) {
    this.getCountries = function () {
        return $http({
            method: "Get",
            url: "/Account/GetCountries"
        });
    };
});

CountriesController.js

/// <reference path="../Services/CountriesService.js" />

angular.module("RegisterApp").controller("CountriesController", function ($scope, CountriesService) {
    getCountries();

    function getCountries() {
        CountriesService.getCountries()
            .success(function (data, status, headers, config) {
            $scope.countries = data;
            $scope.country = $scope.countries[0];
        })
            .error(function (data, status, headers, config) {
            $scope.message = 'Unexpected Error';
        });
    }
});

编辑:移动ng-app,被错误地复制过来,这是我在发布q之前尝试做的改变,对不起

2 个答案:

答案 0 :(得分:0)

您的代码必须是:

<div ng-app="RegisterApp">
   <!-- some beautiful html -->
   <div class="form-group" ng-controller="CountriesController as CountriesCtrl">
        <label class="input-desc">Country</label>
        <select ng-model="country" ng-options="country.Id as country.Name for country in countries">
            <option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
        </select>
    </div>
    <!-- some beautiful html -->
</div>

注意ngApp指令的用法。

另外,检查所有依赖项是否正确注入(我的意思是<head>阻止)

答案 1 :(得分:0)

ng-app必须在ng-controller之前注册(或在同一元素上注册)。您已在子元素(select)中将其注册到具有ng-controller

的元素

将您的HTML更改为:

<div ng-app="RegisterApp" class="form-group" ng-controller="CountriesController as CountriesCtrl">
    <label class="input-desc">Country</label>
    <select ng-model="country" 
      ng-options="country.Id as country.Name for country in countries">
        <option value="{{CountriesCtrl.country.Id}}">{{CountriesCtrl.country.Name}}</option>
    </select>
</div>

看看this JSFiddle。