理解angularjs组件有困难。以前只使用过指令
所以我一直在使用一个控制器一个视图,并且只对我想要重复使用的部分使用指令 现在我要去面试,我被要求了解这个组件,我从来都不知道它的存在。我试图用它替换指令,但甚至不能将简单对象从父控制器传递到组件中理解angularjs组件有困难。以前只使用过指令,angularjs,angularjs-components,Angularjs,Angularjs Components,所以我一直在使用一个控制器一个视图,并且只对我想要重复使用的部分使用指令 现在我要去面试,我被要求了解这个组件,我从来都不知道它的存在。我试图用它替换指令,但甚至不能将简单对象从父控制器传递到组件中 (第一个问题)我一直都在使用$scope。现在我正在阅读组件,我看到到处都使用$ctrl,有什么不同 app.js var myApp= angular.module('bigMoveApp', ['ngRoute', 'testerModule']); myApp.config(['$route
var myApp= angular.module('bigMoveApp', ['ngRoute', 'testerModule']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'app/Views/main.html',
controller: 'ctrlMain'
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('ctrlMain', ['$scope', function ($scope) {
//code
$scope.paragraphToWrite = { text: "let's write something" };
//code
}])
function paragraphController($scope, $element, $attrs) {
var ctrl = this;
ctrl.user = $scope.$parent.textFields.whatWeDo.title;
var x = ctrl.obj;
}
myApp.component('paragraphComponent', {
templateUrl: '/app/Views/paragraphCom.html',
bindings: {
obj : '='
},
controller: paragraphController
})
ctrlMain.js
var myApp= angular.module('bigMoveApp', ['ngRoute', 'testerModule']);
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'app/Views/main.html',
controller: 'ctrlMain'
}).
otherwise({
redirectTo: '/'
});
}]);
myApp.controller('ctrlMain', ['$scope', function ($scope) {
//code
$scope.paragraphToWrite = { text: "let's write something" };
//code
}])
function paragraphController($scope, $element, $attrs) {
var ctrl = this;
ctrl.user = $scope.$parent.textFields.whatWeDo.title;
var x = ctrl.obj;
}
myApp.component('paragraphComponent', {
templateUrl: '/app/Views/paragraphCom.html',
bindings: {
obj : '='
},
controller: paragraphController
})
main.html
<div id="main-body-wrapper">
<...>
<paragraph-Component obj="paragraphToWrite"></paragraph-Component>
<...>
</div>
请帮帮我,我需要在今天结束之前把我的头绕到组件上,我昨天通宵都在读这篇文章,但仍然没有完全理解它。我甚至不了解组件的好处,当指令可以从我的理解中做更多的事情时,别担心,这并不是什么新鲜事。AngularJS组件API是。在幕后,当您使用
.component
API时,它会创建一个指令。引入这些更改是为了使AngularJS迁移到Angular(2+)版本更加平滑。此外,API的可读性看起来也很相似,因为Angular完全基于组件
回到你的问题上来
每当您在定义控制器时使用controllerAs
模式时,所有绑定值都驻留在$scope.controllerias
变量中。最后,如果您看到alias中的内容,您将看到,这个
(上下文)正好填充在那里。在这里,您不应该在控制器中使用$scope
,而是所有东西都将驻留在控制器函数中,该函数只不过是$ctrl
默认控制器别名李>
您在使用组件名称时有输入错误<代码>段落组件
标记应为段落组件
<paragraph-component obj="paragraphToWrite"></paragraph-component>
谢谢现在这很有道理。至于数字2,我修正了输入错误,但在varx=ctrl.obj
行的paragraphComponent.js
下,它仍然显示未定义。噢,nvm我现在找到了原因。结果是我试图太快地获取值,控制器绑定甚至还没有完成。我用$onInit
解决了这个问题。他妈的在这上面浪费了这么多时间。谢谢你,伙计!