I pass scope values to my directive but it's undefined - javascript

I have a problem to pass into my directive 3 parameters from the scope of my controller.
See the directive :
angular.module('app.administration').directive('wcModuleForm', function()
{
return {
restrict: 'E',
scope: {
'module': '=',
'applications': '=',
'standards': '='
},
templateUrl: 'app/administration/directives/module/wc-module-form.tpl.html',
link: function(scope, form)
{
form.bootstrapValidator({...});
}
};
});
And in the html i call the directive :
<wc-module-form
module="moduleForm"
applications="applications"
standards="standards">
</wc-module-form>
The 3 values moduleForm, applications and standards are in my scope controller.
But when i test in the template of the directive, all values are undefined, i don't understand why?
<h4>module : {{(module === undefined) ? 'undefined' : 'defined'}}</h4> -> **undefined**
<h4>applications : {{(applications === undefined) ? 'undefined' : 'defined'}}</h4> -> **undefined**
<h4>standard : {{(standards === undefined) ? 'undefined' : 'defined'}}</h4> -> **undefined**
when i put a watch on 'module' in the link function of the directive with a console.log, nothing at all.
the template of the directive is a bootstrap modal which contain a form to add or edit a module :
<div class="modal fade" id="moduleFormModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">{{ (module.id !== undefined) ? "Ajout d'un module" : "Edition d'un module" }}</h4>
<h4>module : {{(module === undefined) ? 'undefined' : 'defined'}}</h4>
<h4>applications : {{(applications === undefined) ? 'undefined' : 'defined'}}</h4>
<h4>standard : {{(standards === undefined) ? 'undefined' : 'defined'}}</h4>
</div>
<div class="modal-body">
<form id="movieForm" method="post" class="ng-pristine ng-valid bv-form" novalidate="novalidate">
<button type="submit" class="bv-hidden-submit" style="display: none; width: 0px; height: 0px;"></button>
<div class="form-group">
<label class="control-label">Nom</label>
<input type="text" class="form-control" name="name" ng-model="module.name">
</div>
<div class="form-group">
<label class="control-label">Pictogramme</label>
<input type="text" class="form-control" name="picto" ng-model="module.picto">
</div>
<div class="form-group">
<label class="control-label">Couleur</label>
<input type="text" smart-colorpicker class="form-control" name="color" ng-model="module.color">
</div>
<div class="form-group">
<div class="selectContainer">
<label class="control-label">Application</label>
<select class="form-control" name="application" ng-model="module.application_id">
<option ng-repeat="application in applications" value="application.id">{{ application.name }}</option>
</select>
</div>
</div>
<div class="form-group">
<div class="selectContainer">
<label class="control-label">Standard</label>
<select class="form-control" name="standard" ng-model="module.standard_id">
<option ng-repeat="standard in standards" value="standard.id">{{ standard.name }}</option>
</select>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Sauvegarder</button>
</div>
</div>
</div>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
and the controller :
'use strict';
angular.module('app.administration')
.controller('AdministrationCtrl', ['$scope', '$rootScope', '$http', 'APP_CONFIG', function($scope, $rootScope, $http, APP_CONFIG)
{
/**
* différentes applications existantes
* #type [{object}]
*/
$scope.applications = [];
/**
* différentes standards existantes
* #type [{object}]
*/
$scope.standards = [];
/**
* module pour le formulaire
* #type {{}}
*/
$scope.moduleForm = {id: 5,
name: 'Fonction',
standard_id: 2,
application_id: 1,
picto: 'fa fa-gears',
color: '#F20E0E'};
}]);
So, if you have an idea, thanks in advance.

it's good i find a solution :
see the directive :
angular.module('app.administration').directive('wcModuleForm', function()
{
return {
restrict: 'E',
scope: {
module: '=',
applications: '=',
standards: '='
},
templateUrl: 'app/administration/directives/module/wc-module-form.tpl.html',
link: function($scope, form)
{
form.bootstrapValidator({...});
}
};
});
i add a '$' to scope and it's good :)
but i don't understand why it's work now so if someone know why, he will can explain it to me. thanks :)

Is this what you are looking for?
(function () {
'use strict';
angular
.module('app.administration')
.directive('wcModuleForm', wcModuleForm);
wcModuleForm.$inject = [];
function wcModuleForm() {
return {
restrict: 'E',
scope: {
module: '=',
applications: '=',
standards: '='
},
controller: function ($scope) {
form.bootstrapValidator({
module: $scope.module,
applications: $scope.applications,
standards: $scope.standards
});
},
template: '<div>{{ module }}{{ applications }}{{ standards }}</div>'
}
}
}());

Try with removing the quotes from your scope attributes in wcModuleForm directive.
Like this:
return {
restrict: 'E',
scope: {
module: '=',
applications: '=',
standards: '='
},
templateUrl: 'app/administration/directives/module/wc-module-form.tpl.html',
link: function(scope, form)
{
form.bootstrapValidator({...});
}
};
If it doesn't work, maybe module is a predefined attribute. Try using another name. Like <directive data-application="..."></directive> will not work because data is reserved.

Related

ng-options as directive parameter

So, I have the same question asked on this question, sadly, no one has answered, so, here it goes again
I'm trying to create a select directive, where I can send the ng-options as a parameter.
This is my directive
app.directive('dropDown', function () {
return {
restrict: 'E',
template: function (element, attrs) {
return '<div class="col-sm-{{labelCol}} control-label">' +
'<label>{{label}}:</label>' +
'<div>' +
'<div clas="col-sm-{{controlCol}}">' +
'<label style="cursor:pointer" ng-show="!edit && forEdit" ng-disabled="disabled" ng-click="edit = true;">{{ngModel}}</label>' +
'<i ng-show="!edit && forEdit && !disabled" class="fa fa-pencil-square-o" style="cursor:pointer" aria-hidden="true" ng-click="edit = true;"></i>' +
'<select name="{{name}}" ng-change="ngChange" ng-blur="edit = false" ng-show="edit || !forEdit" class="form-control" ng-model="ngModel" ng-required="required" ng-options={{options}}/>' +
'</div>'
},
replace: true,
scope: {
ngModel: '=',
ngChange: '&',
label: '#',
labelCol: '#',
controlCol: '#',
type: '#',
name: '#',
disabled: '=',
required: '=',
forEdit: "=",
options: "#"
},
link: function (scope, element, attrs) { },
compile: function (element, attrs) {
if (!attrs.labelCol) attrs.labelCol = '4';
if (!attrs.controlCol) attrs.controlCol = '8';
if (!attrs.required) attrs.required = false;
if (!attrs.disabled) attrs.disabled = false;
if (!attrs.forEdit) attrs.forEdit = false;
attrs.edit = !attrs.forEdit;
}
}
})
And this is a implementation of the directive
<div class="row">
<drop-down ng-model="site" for-edit="true" label="Site Test" options="x.SITE_CODE as x.SITE_NAME for x in sites"></drop-down>
</div>
<div class="row">
<drop-down ng-model="site1" for-edit="true" label="Site Test" options="x for x in sites1"></drop-down>
</div>
And I'm getting the same response
Error: [$parse:syntax] Syntax Error: Token 'in' is an unexpected token
at column 3 of the expression [x in sites1] starting at [in sites1].
Error: [$parse:syntax] Syntax Error: Token 'as' is an unexpected token
at column 13 of the expression [x.SITE_CODE as x.SITE_NAME for x in
sites] starting at [as x.SITE_NAME for x in sites].
Any idea how to achieve my desired result?
Edit1:
If it help, here's the arrays that should be filling the selects
$scope.sites = JSON.parse("[{\"SITE_CODE\":\"1\",\"SITE_NAME\":\"SITE1\",},{\"SITE_CODE\":\"2\",\"SITE_NAME\":\"SITE2\"},{\"SITE_CODE\":\"3\",\"SITE_NAME\":\"SITE3\"},{\"SITE_CODE\":\"4\",\"SITE_NAME\":\"SITE4\"}]");
$scope.sites1 = ["SITE1", "SITE2", "SITE3", "SITE4"];
Edit 2:
Added the error for the more complex ng-options sentence
Edit 3:
So, I just realized that, I'm setting the ngOptions as a 2 way databinding field on the scope, as, it's not necesary, so I changed it from = to # and now, I'm getting another error message
Error: [$compile:ctreq] Controller 'select', required by directive 'ngOptions', can't be found!
Which, it's unreasonable, as I'm indeed setting the ngOptions, and I can verify it on the compile
Edit 4:
So, after some testing, I'm finally getting my controls rendered, but sadly, withouth values
The selects are clearly on the controller div
<div class="content" ng-controller="testController">
<div class="row">
<drop-down ng-model="site" for-edit="true" label="Site Test" options="x for x in sites"></drop-down>
</div>
<div class="row">
<drop-down ng-model="site" label="Site Test" options="x for x in sites"></drop-down>
</div>
<div class="row">
<drop-down ng-model="site1" for-edit="true" label="Site Test" options="x for x in sites1"></drop-down>
</div>
</div>
The controller indeed has this collections
app.controller('testController', ['$scope', function ($scope) {
$scope.sites = JSON.parse("[{\"SITE_CODE\":\"1\",\"SITE_NAME\":\"SITE1\",},{\"SITE_CODE\":\"2\",\"SITE_NAME\":\"SITE2\"},{\"SITE_CODE\":\"3\",\"SITE_NAME\":\"SITE3\"},{\"SITE_CODE\":\"4\",\"SITE_NAME\":\"SITE4\"}]");
$scope.sites1 = ["SITE1", "SITE2", "SITE3", "SITE4"];
}]);
But my rendered controls comes without any values
This is the rendered html for one of the controls
<div ng-model="site" label="Site Test" options="x for x in sites" class="ng-isolate-scope ng-valid">
<div class="col-sm-4 control-label"><label class="ng-binding">Site Test:</label></div>
<div class="col-sm-8">
<label style="cursor:pointer" ng-show="!edit && forEdit" ng-disabled="disabled" ng-click="edit = true;" class="ng-binding ng-hide"></label>
<i ng-show="!edit && forEdit && !disabled" class="fa fa-pencil-square-o ng-hide" style="cursor:pointer" aria-hidden="true" ng-click="edit = true;"></i>
<select name="" ng-change="ngChange" ng-blur="edit = false" ng-show="edit || !forEdit" class="form-control ng-pristine ng-valid ng-valid-required ng-touched" ng-model="ngModel" ng-required="required" ng-options="x for x in sites">
<option value="?" selected="selected"></option>
</select>
</div>
</div>
At least now I'm getting my controls rendered, now, on to show some values on them
The syntax ng-options="x in sites1" is incorrect.
In it's most simplest form it should be label for value in array:
ng-options="x for x in sites1"
Also check out the angular docs for ngOptions to see all of the permitted argument forms.
Well, after much testing, I finally am able to achieve my desired result.
I'll leave the directive here to whoever might want to use it, as it allows to
Set a desired options string
Set a property to show in case we store the complete object in the model
Disabled status, that will only show the model value
Inline edit of the value
var app = angular.module("app", []);
app.controller('testController', ['$scope', function($scope) {
$scope.sites = JSON.parse("[{\"SITE_CODE\":\"1\",\"SITE_NAME\":\"TEST 1\"},{\"SITE_CODE\":\"2\",\"SITE_NAME\":\"TEST 2\"},{\"SITE_CODE\":\"3\",\"SITE_NAME\":\"TEST 3\"},{\"SITE_CODE\":\"4\",\"SITE_NAME\":\"TEST 4\"}]");
$scope.sites1 = ["TEST 1", "TEST 2", "TEST 3"];
}]);
app.directive('dropDown', function() {
return {
restrict: 'E',
require: 'ngOptions',
template: function(element, attrs) {
return '<div>' +
'<div class="col-sm-{{labelCol}} control-label">' +
'<label>{{label}}:</label>' +
'</div>' +
'<div class="col-sm-{{controlCol}}">' +
'<label ng-show="!edit && forEdit">{{ngModel[textValue] !== undefined ? ngModel[textValue] : ngModel}}</label> ' +
'<span ng-show="!edit && forEdit && !disabled" class="fa fa-pencil-square-o" style="cursor:pointer" aria-hidden="true" ng-click="edit = true;">click here for edit</span>' +
'<select name="{{name}}" ng-change="ngChange" ng-blur="edit = false" ng-show="edit || !forEdit" class="form-control" ng-model="ngModel" ng-required="required" ng-options="{{options}}"/>' +
'</div>' +
'</div>';
},
replace: true,
scope: {
ngModel: '=',
ngChange: '&',
label: '#',
labelCol: '#',
controlCol: '#',
type: '#',
name: '#',
disabled: '=',
required: '=',
forEdit: "=",
options: "#",
items: "=",
textValue: "#"
},
compile: function(element, attrs) {
if (!attrs.labelCol) attrs.labelCol = '4';
if (!attrs.controlCol) attrs.controlCol = '8';
if (!attrs.required) attrs.required = false;
if (!attrs.disabled) attrs.disabled = false;
if (!attrs.forEdit) attrs.forEdit = false;
if (attrs.disabled)
attrs.forEdit = "true";
attrs.edit = !attrs.forEdit;
},
link: function(scope, element, attrs) {
},
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div class="" ng-controller="testController">
<div class="row">
<drop-down ng-model="site" for-edit="true" label="Site Test Inline" text-value="SITE_NAME" options="x.SITE_NAME for x in items" items="sites"></drop-down>
<drop-down ng-model="site1" for-edit="false" label="Site Test Select" options="x for x in items" items="sites1"></drop-down>
<drop-down ng-model="site1" disabled="true" label="Site Test Disabled" options="x for x in items" items="sites1"></drop-down>
</div>
</div>
</div>

"Controller" is not registered angularjs

I have created a new project, but got a problem which I am not able to fix.
Here's my example:
I have this error :
"Error: [$controller:ctrlreg] The controller with the name 'PostController' is not registered."
Connexion.html
<section id="login" ng-controller="PostController as postCtrl">
<div class="container center-bloc">
<div class="row">
<div class="col-xs-12">
<div class="form-wrap">
<div class="text-center">
<img id="logo" style="max-width:100%;" src="img.png">
</div>
<h2 id="ResultConnexion"></h2>
<form role="form" id="login-form" ng-submit="postCtrl.Search1()" method="POST" autocomplete="off">
<div class="form-group">
<input id="userLogin" required autofocus ng-model="postCtrl.inputData.username" type="text" name="user" id="email" class="form-control" placeholder="exemple#example.com">
</div>
<div class="form-group">
<input id="userPassword" required ng-model="postCtrl.inputData.password" type="password" name="mdp" id="key" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-custom btn-lg btn-block" ng-disabled="login.$invalid" >Connexion</button>
<div class="alert alert-danger" ng-show="errorMsg">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">
×</button>
<span class="glyphicon glyphicon-hand-right"></span> {{errorMsg}}
</div>
<div></div>
</form>
<hr>
</div>
</div>
</div>
</div>
index. js
'use strict';
var routeApp = angular.module("routeApp", ["ngRoute"]);
routeApp.config(function($routeProvider) {
$routeProvider
.when("/", {
url: "/",
templateUrl : "template/connexion.html",
controller : "PostController"
})
});
var routeAppControllers = angular.module('routeAppControllers',['ngRoute']);
routeAppControllers.controller('PostController', ['$scope', '$http', function($scope, $http) {
this.postForm = function() {
var Pass = {"user":(this.inputData.username),"mdp":(this.inputData.Password)};
$http({
method: 'POST',
url: '/',
data: Pass,
headers: {'Content-Type': 'application/json'}
})
.then(function(response) {
if ( response.data.resultat == 0) {
window.location.href = '/information';
alert('hello')
} else {
$scope.errorMsg = 'Bad';
}
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
})
}
}]);
Can anybody help?
You have two separate modules showing and neither is injected in the other.
Assuming your ng-app uses routeApp you need to inject routeAppControllers module into routeApp module
var routeApp = angular.module("routeApp", ["ngRoute", "routeAppControllers"]);
Also you only need to inject ngRoute once.
As noted in other answer you only use ng-controller when it is not declared in routing config also, or you end up with multiple controller instances
I think you should remove ng-controller="PostController as postCtrl"> from template .Because you defined it in route . and also change to below.
.when("/", {
url: "/",
templateUrl : "template/connexion.html",
controller : "PostController as postCtrl"
})
another tip that recommended you declare var vm = this and use vm instead of this
vm.postForm = function() {...}

Form with angularjs doesn't fill all fields

I'm using angularjs to create a modal used by a form.
In my javascript I receive only two fields of my form (name and clientVersion) the other two are omitted and I don't know why.
This is my modal:
<div class="modal" id="addUserModal" data-ng-app="myApp">
<div class="modal-dialog" data-ng-controller="modalController">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">New user</h4>
</div>
<div class="modal-body">
<form novalidate class="simple-form">
<!-- form start -->
<div class="box-body">
<div class="form-group">
<label>Name</label> <input id="name" type="text"
data-ng-model="newUser.name" class="form-control"
maxlength="30" placeholder="Version name" required>
</div>
<div class="form-group">
<label>Role</label> <select class="form-control select2"
style="width: 100%;" name="role" data-ng-model="newUser.role"
data-ng-options="user.idRole as role.role for role in roles track by role.role">
</select>
</div>
<div class="form-group">
<label>Client Version </label> (optional) <select
class="form-control select2" style="width: 100%;"
name="version" data-ng-model="newUser.clientVersion"
data-ng-options="version.idClientVersion as version.name for version in versions track by version.name">
</select>
</div>
<div class="form-group">
<label>Enable </label> <input type="checkbox"
data-ng-model="newUser.enabled" name="my-checkbox" checked>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default pull-left"
data-dismiss="modal">Close</button>
<button id="uploadVersionButton" type="button"
class="btn btn-primary" data-ng-click="createUser(newUser)">Create
user</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
In my javascript code I have
//Angular section for Select2 of modal create user
var app = angular.module('myApp',[]);
app.controller('modalController', function($scope, $http) {
$http({
method: 'GET',
url: 'roles'
}).then(function successCallback(response) {
$scope.roles = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$http({
method: 'GET',
url: 'version',
}).then(function successCallback(response) {
$scope.versions = response.data.result;
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
$scope.createUser = function(newUser) {
$scope.master = angular.copy(newUser);
};
});
and newUser has only those two fields. Do you know why?
First error is in
data-ng-options="role.idRole as role.role for role in roles track by role.role"
I gave the wrong idRole.
The checkbox is a prolem of bootstrap plugin, without it all works.
I found this directive and work:
app.directive('bootstrapSwitch', [
function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
element.bootstrapSwitch();
element.on('switchChange.bootstrapSwitch', function(event, state) {
if (ngModel) {
scope.$apply(function() {
ngModel.$setViewValue(state);
});
}
});
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
if (newValue) {
element.bootstrapSwitch('state', true, true);
} else {
element.bootstrapSwitch('state', false, true);
}
});
}
};
}
]);
but perhaps it is better to use
$('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state)
and store state into a variable.

Cannot get the variable in ng-model in directive template

I have a directive for comment input as follows, I want to reset the form after the user posted the comment. However, I can not get the newComment value of ng-model in link function. How to solve such problem.
commenting.html
<div class="directive__commenting">
<div class="col-content">
<h4>{{title}}({{count}})</h4>
<form class="form" name="commentForm" ng-submit="createComment(commentForm, newComment)" ng-if="isLoggedIn()">
<div class="form-group">
<textarea class="form-control" name="newComment" rows="3" placeholder="你怎么看?" ng-model="newComment" required></textarea>
</div>
<div class="right">
<span id="count-words" ng-class="{'red': isWordsExceeded(newComment)}">{{140 - newComment.length}}</span>
<button class="send-button btn btn-default" type="submit" ng-disabled="isWordsExceeded()">{{btnActionTitle}}</button>
</div>
</form>
</div>
</div> <!-- #create-comment -->
commenting.directive.js
'use strict';
angular.module('myapp')
.directive('commenting', function (Auth) {
return {
templateUrl: 'components/directive/commenting/commenting.html',
restrict: 'EA',
scope: {
title: '=',
count: '=',
btnActionTitle: '=',
action: '='
},
link: function (scope) { //, element, attrs
scope.isLoggedIn = Auth.isLoggedIn;
scope.isWordsExceeded = function (newComment) {
return newComment && newComment.length > 140;
}; //- isWordsExceeded
scope.createComment = function (form, newComment) {
scope.action(form, newComment)
.then(function () { //success
// clear the form, however here scope.newComment is undefined
})
.catch(function () { //fail
});
};
}
};
});
The directive is added in a html file as follows.
<div class="row" id="create-comment">
<commenting title="'Comments'" count="model.comments.length" btn-action-title="'Submit comment'" action="createComment"></commenting>
</div> <!-- #create-comment -->
Try to access through scope like
scope.newComment

Controller on Modal not working on AngularJS

I have a main users page with users, if you select a user, a modal is opened and should show the user information.
The problem is that the $scope doesn't seem to be working, as it doesn't show the user data on the modal. But if I show that user data anywhere on the main users page, it works fine.
I have this controller:
function userController($scope, $modal, $http, $rootScope) {
var usrCtrl = this;
$scope.users = null;
$scope.openUserForm = function () {
var modalInstance = $modal.open({
templateUrl: 'views/modal_user_form.html',
controller: userController,
windowClass: "animated flipInY"
});
};
var session = JSON.parse(localStorage.session);
$http({
method: 'GET',
url: $rootScope.apiURL+'getAllClientUsers/'+session,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response){
if(response.ErrorMessage === null && response.Result !== null){
$scope.users = response.Result;
}
});
//**This is the code that opens the modal
$scope.editViewUser = function(user){
for (var key in $scope.users) {
if($scope.users[key].SecUserId === user){
$scope.selectedUser = $scope.users[key];
}
}
$scope.openUserForm();
};
};
And this modal:
<div ng-controller="userController">
<div class="inmodal">
<div class="modal-header">
<h4 class="modal-title">Create or Edit User</h4>
<small class="font-bold">Use this modal to create or edit a user</small>
</div>
<div class="modal-body">
<form method="get" class="form-horizontal">
<div class="form-group"><label class="col-sm-2 control-label">Nombre</label>
<div class="col-sm-10"><input ng-model="selectedUser.FirstName" type="text" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Apellido</label>
<div class="col-sm-10"><input ng-model="selectedUser.LastName" type="text" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Usuario</label>
<div class="col-sm-10"><input ng-model="selectedUser.UserName" type="text" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Email</label>
<div class="col-sm-10"><input ng-model="selectedUser.Email" type="email" class="form-control"></div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Activo</label>
<div class="col-sm-10">
<div><label> <input ng-model="selectedUser.FirstName" type="checkbox" value=""></label></div>
</div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Email Verificado</label>
<div class="col-sm-10">
<div><label> <input ng-model="selectedUser.FirstName" type="checkbox" value=""></label></div>
</div>
</div>
<div class="form-group"><label class="col-sm-2 control-label">Privilegios</label>
<div class="col-sm-10">
<select class="form-control m-b" name="account">
<option ng-repeat="priv in selectedUser.EffectivePrivileges">{{ priv }}</option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" ng-click="cancel()">Close</button>
<button type="button" class="btn btn-primary" ng-click="ok()">Save changes</button>
</div>
</div>
</div>
I tried injecting the controller and also using the ng-controller, and scope property for modal.
What am I missing?
The problem is that modal template is compiled in the scope which doesn't inherit from your $scope. To make a connection between them you can tell modal to create a new child scope of your scope:
$scope.openUserForm = function () {
var modalInstance = $modal.open({
scope: $scope, // <----- add this instruction
templateUrl: 'views/modal_user_form.html',
controller: userController,
windowClass: "animated flipInY"
});
};
Generally, the modal would have its own controller rather than point to the controller that its called from. You would inject the model (selectedUser) into the modal controller, work on it, then pass it back to parent. Also, you can give user option to cancel in which case no changes are made to parent controller model.
Modal controller:
app.controller('UserModalController', [
'$scope',
'$modalInstance',
'selectedUser',
function ($scope, $modalInstance, selectedUser) {
$scope.selectedUser = selectedUser;
$scope.cancel= function () {
// user cancelled, return to parent controller
$modalInstance.dismiss('cancel');
};
$scope.save = function () {
// close modal, return model to parent controller
$modalInstance.close($scope.selectedUser);
};
]);
Changes to main controller:
var modalInstance = $modal.open({
templateUrl: 'views/modal_user_form.html',
controller: 'UserModalController',
windowClass: "animated flipInY",
resolve: {
selectedUser: function() {
return $scope.selectedUser;
}
}
});
modalInstance.result.then(function(updatedUser) {
// deal with updated user
}, function() {
// modal cancelled
});

Categories