David Shaw David Shaw - 23 days ago 7
AngularJS Question

Simple example can't access scope

I am trying to learn AngularJS, and going through an older tutorial I have built out a simple app. It has an index.html and two partial views which are loaded via ui-router. I know it's not separated into different files -- this is a learning project only.

The problem is that $scope does not seem to be available in View1 or in its called JS function , so

ng-repeat
doesn't seem to find anything to display, and
addCustomer
cannot see $scope.newCustomer.name. I am sure that I am missing something simple.

index.html:

<!DOCTYPE html>
<html ng-app="demoApp">

<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<script src="js/angular/angular.js"></script>
<script src="js/angular-ui-router/angular-ui-router.js"></script>
<!-- your app's js -->
<script>

var demoApp = angular.module('demoApp', ['ui.router']); // [] is for dependencies

// routes
demoApp.config(function($stateProvider, $urlRouterProvider) {
var nameState = {
name: 'name',
url: '/view1',
controller: 'SimpleController',
templateUrl: 'partials/View1.html'
}

var cityState = {
name: 'city',
url: '/view2',
controller: 'SimpleController',
templateUrl: 'partials/View2.html'
}

$stateProvider.state(nameState);
$stateProvider.state(cityState);

$urlRouterProvider.otherwise('/view1');
});

// controller

demoApp.controller("SimpleController", function ( $scope, $log ) {
$scope.log = $log;

$scope.customers = [{name: 'John Doe', city:'New York'},
{name: 'Jake Smith', city:'Atlanta'},
{ name: 'Jane Doe', city:'San Francisco'}];


$scope.addCustomer = function () {
$log.log("Add customer");
$scope.customers.push(
{name: $scope.newCustomer.name, city: $scope.newCustomer.city}
);
};
});

</script>
</head>

<body>
<div>
<!-- placeholder for views inserted by ui-router -->
<ui-view></ui-view>
</div>
</body>

</html>


View1.html:

<div class="container">
<h2>View 1</h2>
Name: <input type="text" ng-model="filter.name" /> You entered: {{filter.name}}
<div class="container">
<h3> Loop </h3>
<ul>
<li ng-repeat="cust in $scope.customers | filter:filter.name">{{ cust.name }} - {{ cust.city }}</li>
</ul>
<br /> Customer Name:
<input type="text" ng-model="newCustomer.name" />
<br /> Customer City:
<input type="text" ng-model="newCustomer.city" />
<br />
<br />
<button ng-click="addCustomer()">Add Customer</button>
</div>
<a href="#/view2">Switch to View 2</a>
</div>

Answer

Use only

ng-repeat="cust in customers"