javascript - How to reuse HTML/Controller for Add/Edit user in AngularJs -
i have 2 separate html templates add / edit user , hence 2 separate controllers. how can have 1 html file , 1 controller both add/edit functionality.
add user
<div> <label>firstname</label> <div> <input type="text" name="name" data-ng-model="register.student.firstname"> </div> </div> <div> <label>lastname</label> <div> <input type="text" name="name" data-ng-model="register.student.lastname"> </div> </div>
edit user
<div> <label>firstname</label> <div> <input type="text" name="name" data-ng-model="student.student.firstname"> </div> </div> <div> <label>lastname</label> <div> <input type="text" name="name" data-ng-model="student.student.lastname"> </div> </div>
addcontroller initialize firstname , last name null value. not case in editcontroller.
$scope.register = { user: { firstname: '', lastname: '', };
my route configuration
templateurl: '/app/users/newstudent.html', controller: 'newstudentcontroller', controllerurl: '/app/users/newstudentcontroller.js', templateurl: '/app/users/editstudent.html', controller: 'editstudentcontroller', controllerurl: '/app/users/editstudentcontroller.js',
club both html
files , name student.html
, club both controller
files , name student.js
.
student.js
app.module('myapp', []).controller('studentcontroller', function () {})
your route config:
templateurl: '/app/users/student.html', controller: 'studentcontroller', controllerurl: '/app/users/student.js',
update
demo: http://jsfiddle.net/softvar/uh17tseh/1/
html:
<div ng-app="myapp" ng-controller="mycontroller"> <div ng-repeat="stud in students"> <div ng-hide="iseditform"> <span>{{stud.name}} - {{stud.age}}</span> <button ng-click="iseditform=true;">edit student</button> </div> <div ng-show="iseditform"> <label>enter name</label><input ng-model="stud.name" /> <label>enter age</label><input ng-model="stud.age" /> <button ng-click="iseditform=false;">save</button> </div> </div> <br/><br/> <div ng-hide="isaddform"> <button ng-click="isaddform=true;">add student</button> </div> <div ng-show="isaddform"> <label>enter name</label><input ng-model="newstudent.name" /> <label>enter age</label><input ng-model="newstudent.age" /> <button ng-click="addstudent()">add</button> <button ng-click="isaddform=false;">cancel</button> </div> </div>
js:
var app = angular.module('myapp', []); app.controller('mycontroller', function ($scope) { $scope.students = [ {"name": "abc", "age": 21}, {"name": "def", "age": 22}, {"name": "ghi", "age": 23}, {"name": "xyz", "age": 24} ]; $scope.newstudent = {}; $scope.addstudent = function () { if ($scope.newstudent.name && $scope.newstudent.age) { $scope.students.push({"name": $scope.newstudent.name,"age": $scope.newstudent.age}); $scope.isaddform = false; } }; });
Comments
Post a Comment