·Question
Using this in the controller does not work (below), why?
//---------------------------------------------------------
// Employee number
function empnumberController(employee, employeeFactory) {
this.empInstance=employee;
This.employeeFactoryInstance=employeeFactory;
}
// -------------------------------------------------
// Employee Scale
function empscaleController(employeeFactory) {
This.employeeFactoryInstance=employeeFactory;
}
$scope will work (below)
//---------------------------------------------------------
// Employee number
function empnumberController($scope, employee, employeeFactory) {
$scope.empInstance=employee;
$scope.employeeFactoryInstance=employeeFactory;
}
// -------------------------------------------------
// Employee Scale
function empscaleController($scope, employeeFactory){
$scope.employeeFactoryInstance=employeeFactory;
}
I don't really want to use $scope, so what should I do with this?
·Background
I wrote a program to process and pass values between controllers that are not parent-child relationships.
Enter the number of employees and return the size.
// Employee Factory
app.factory("employeeFactory", function(employee){
varempInstance=employee;
US>return{
getemployeeFullName: function(){
if (0<empInstance.Number&&empInstance.Number<=10){
empInstance.Scale="1-10 people";
} else if (10<empInstance.Number&&empInstance.Number<=30){
empInstance.Scale="11-30 people";
} …omitted… else if (1000<empInstance.Number) {
empInstance.Scale="1,001 people~";
} else{
empInstance.Scale="";
}
returnempInstance.Scale;
}
};
});
app.value("employee", {Number:", Scale:""});
// component
app.component('myEmplyenumber', {
bindings: ...omitted...
, controller:empnumberController
, template: '<input type="number" ng-model="empInstance.Number">'
});
app.component('myEmplyescale', {
bindings: ...omitted...
, controller:empscaleController
, template: '{{employeFactoryInstance.getemployeFullName()}}'
});
·What I tried
br/>
in the controller
console.dir($scope);
and
console.dir(this);
It was completely different when I tried.
I look forward to your kind cooperation.
angularjs
If you specify controller
in the component
module, $ctrl
is required to use the value set to this
in the template.
Note: https://docs.angularjs.org/guide/component
var myMod=angular.module('myMod', ['ngRoute']);
myMod.component('home', {
template: '<h1>Home</h1>>Hello, {{$ctrl.user.name}}!</p>',
controller:function(){
this.user={name:'world'};
}
});
myMod.config(function($routeProvider){
$routeProvider.when('/', {
template: '<home></home>'
});
});
See controllerAs notation for more information.
© 2024 OneMinuteCode. All rights reserved.