click doesn't fire from within template

In AngularJS, can methods be called from within templates without a directive or routeProvider to bind the scope?

My specific problem is that my main controller (AppCtrl) is located on the body of my index page. On the index I use an ngView to pull in templates according to routing. Each routeProvider has its own controller except for the default template. I assumed that because of scope inheritance I could use methods defined with the AppCtrl from the template but trying to just do a simple alert or console.log doesn't register anything. I know the $scope is getting to the template because my data shows up correctly.

This seems to be a $scope issue but I'm not certain how to address it. Do I need to create a directive to explicitly bind them?

index.html

<body ng-controller="AppCtrl">
   <div ng-view></div>
</body>

app.js

var myApp = angular.module('myApp', [])
.config(function($routeProvider) {
  .when('/', {
    templateUrl: 'partials/list.html'
  }),
  .when('/info/:id, {
    templateUrl: 'partials/info.html'
    controller: 'InfoCtrl'
  });
});

controllers.js

var controllers = {};
controllers.AppCtrl = function($scope, $location, Factory) {
  ...
  $scope.doSomething = function() {
    alert('hello');
  };
};
myApp.controller(controllers);

list.html

<a href="#" ng-click="doSomething()">Do Something</a> // no response

I seem to have found the root of my problem. As described, using a function did work. When I went back to address my specific problem, once again the function refused to work. Turns out it wasn't a scope problem but a binding problem. The example I gave wasn't accurate but did help me isolate the problem. I'll demonstrate:

<!-- alert fires, tries to find '#' in location, binded values do not update -->
<a href="#" ng-click="addOne()">Add 1</a> 

<!-- key binding does not update -->
<a href="#" ng-click="key = key+1" ng-init="key=0">Add 1</a>

<!-- key updates -->
<a ng-click="key = key+1" ng-init="key=0">Add 1</a>

For whatever reason, including an href was preventing the binded value from updating. Does anyone know if there's a "preventDefault" that can be used as a workaround so that hrefs can be included for validation? It seems that this is either a bug or ng-click is only intended to be used with buttons.

链接地址: http://www.djcxy.com/p/30972.html

上一篇: 将对象推入数组中,无法使用模态角度js

下一篇: 点击不会从模板中触发