angularjs 组件components(五)

文章目录

    • 文章参考
    • Component 快速使用入门

文章参考

  1. angularjs component
  2. Component 官方文档

Component 快速使用入门

  1. 在父组件页面中的HTML中使用组件
<div>
  myinfo ---- {{myname}}
  <my-info-details hero="myname" on-herofunc='testHttpFunc()'>my-info-details>
div>

父组件传递方法给子组件,需要使用 on打头,并且将驼峰转为 “-”,

app.controller('myinfoController', [
  '$scope',
  '$state',
  '$stateParams',
  '$http',
  function ($scope, $state, $stateParams, $http) {
    console.log($stateParams)
    console.log($state)

    $scope.myname = 'huangbaio'

    // 定义 testHttpFunc 方法
    $scope.testHttpFunc = function () {
      $http.get('http://10.19.171.20:8899/mock/5f1579a476afe424e0520f05/example/query').then(function (res) {
        console.log(res)
		// 改变数据,会影响到子组件
        $scope.myname = 'huanghaili'
      })
    }
  },
])
  1. 定义一个组件名为 myInfoDetails 的组件
    1. 组件首字母一定要小写,否则会报错,无法依赖注入
    2. 驼峰命名全部转为 “-”
    3. 父组件传递属性给子组件,使用 “=”(双向传递,不推荐) 或者 “<”(单项传递)
    4. 定义的事件一定要以"on"打头,使用驼峰命名; 尝试用多个驼峰命名,怎么尝试都不成功
;(function (angular) {
  function MyInfoDetailController($scope, $timeout) {
    var ctrl = this
    $scope.parrentPropHero = this.hero
    console.log(this)
    debugger
    $timeout(function () {
      ctrl.hero = 'huanghai lilinag';
    }, 1000)

    $scope.testAction = function () {
	  // 调用父组件传递过来的方法 
      ctrl.onHerofunc()
    }
  }

  // 组件的名字 一定要小写字母打头,否则会提示注入失败
  angular.module('myApp').component('myInfoDetails', {
    // 路径需要以 index.html 为参考点
    templateUrl: './components/MyInfoDetails/MyInfoDetailTemplate.html',
    controller: MyInfoDetailController,
    bindings:{
      hero: '=',
      onHerofunc: '&'
    }
  })
})(angular)
<div>
  <div>MyInfoDetailTemplatediv>
  <div>父组件传递的参数: {{parrentPropHero}}div>
  <button ng-click="testAction()">测试父组件传递的方法button>
div>

你可能感兴趣的:(angularjs,&,ionic,&)